开发者社区> 问答> 正文

在Tkinter GUI中显示Python脚本的输出

我是python新手&请求这个社区的专家的帮助。我试图在我的Tkinter GUI中显示以下脚本的输出。我遵循了StackOverflow上提供的许多解决方案,但不幸的是,我无法在我的代码中实现这些解决方案。我需要帮助在我的Tkinter GUI中显示以下脚本的输出。因此,我可以在Tkinter小部件中显示输出。

import os
import tkinter as tk
import cv2
import numpy as np
from PIL import Image
from PIL import ImageTk

class Difference_Button(Sample_Button, Button):
   def on_click_diff_per_button(self, diff_per):
      threshold = 0.8  # set threshold
       resultsDirectory = 'Data/Differece_images'
       sourceDirectory = os.fsencode('Data/images')
       templateDirectory = os.fsencode('Data/Sample_images')
       detectedCount = 0

       for file in os.listdir(sourceDirectory):
           filename = os.fsdecode(file)
           if filename.endswith(".jpg") or filename.endswith(".png"):

               print(filename)

               img = cv2.imread('Data/images/' + filename)
               im_grayRef = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

               for templateFile in os.listdir(templateDirectory):
                   templateFilename = os.fsdecode(templateFile)

                   if filename.endswith(".jpg") or filename.endswith(".png"):
                       Sample_image = cv2.imread('Data/Sample_images/' + templateFilename, 0)
                       #im_graySam = cv2.cvtColor(Sample_image, cv2.COLOR_BGR2GRAY)
                       cv2.waitKey(0)
                       w, h = Sample_image.shape[::-1]

                       score = cv2.matchTemplate(im_grayRef,Sample_image,cv2.TM_CCOEFF_NORMED)
                       #diff = (diff * 255).astype("uint8")
                       cv2.waitKey(0)
                       diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100)
                       # res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
                       loc = np.where(score >= threshold)

                       if (len(loc[0])):
                           detectedCount = detectedCount + 1
                           for pt in zip(*loc[::-1]):
                               cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
                       cv2.imwrite(resultsDirectory + '/diff_per_' + filename + '.jpg', img)
                       Difference_per_label.config(text='diff_per ' + filename + "_&_" + templateFilename + ' saved')
                       print('diff_per ' + filename + "_&_" + templateFilename + ' saved')
                           # break
               #print('detected positive ' + str(detectedCount))
               continue
           else:
               continue


if __name__ == '__main__':


   root = tk.Tk()
   root.title('Image GUI')
   root.geometry('1280x960')
   os.makedirs('Data/Differece_images', exist_ok=True)
   pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
   pw_left.pack(side='left',anchor='nw')
   pw_left = tk.Frame(root, relief='ridge', borderwidth=4)
   pw_left.pack(side='left', anchor='nw')
   frame7 = tk.Frame(pw_left, bd=2, relief="ridge")
   frame7.pack()
   difference_button = Difference_Button(root, frame7)
   Difference_per_label = tk.Label(frame7, text='print', width=40, bg='white', height = '5')
   Difference_per_label.pack(fill=tk.X)
   Diff_label = tk.Label(frame7, textvariable= 'diffvalue', width=40, bg='white', height = '5')
   Diff_label.pack(fill=tk.X)
   Difference_button = tk.Button(frame7, text='Difference',
                                 command=lambda: difference_button.on_click_diff_per_button(Difference_per_label))
   Difference_button.pack(side='bottom', padx=5, pady=5)
   root.mainloop()

帮助需要的部分: 注意: 任何帮助将不胜感激。提前谢谢。 Req:只有在Help Required部分的所有解决方案都已解决时,才能关闭答案。 问题来源StackOverflow 地址:/questions/59387264/show-output-of-python-script-in-tkinter-gui

展开
收起
kun坤 2019-12-25 21:38:33 831 0
1 条回答
写回答
取消 提交回答
  • print()只在屏幕上发送文本。它从不返回显示的文本。若要赋值给变量,请使用它而不使用print() - ie。

    diffvalue = "Image similarity %ge of_{}_&_{}_is {}".format(filename, templateFilename, score * 100)
    

    现在你可以在标签,文本或列表框中显示文本 要将文本追加到标签,您必须从标签获取旧文本,将新文本连接到旧文本,然后再次将所有文本放入标签-即

    new_text = 'diff_per {}_&_{} saved'.format(filename, templateFilename)
    Difference_per_label["text"] = Difference_per_label["text"] + "\n" + new_text
    

    或更短的wiht +=

    Difference_per_label["text"] += "\n" + new_text
    

    因为tkinter(和其他gui)不会在你改变标签中的文本时更新窗口中的窗口小部件,但是当它结束由按钮执行的函数并返回到mainloop时,你可能不得不在改变标签中的文本后使用root.update()来迫使mainloop()在窗口中重新绘制windgets。 要抛出异常,需要使用raise(),而不是try/except来捕获异常。 要测试是否没有文件,您必须从os.listdir()获取所有数据作为列表,使用endswith()过滤列表,并检查列表是否为空。

    import os
    
    sourceDirectory = '.'
    
    all_files = os.listdir(sourceDirectory)
    all_files = [os.fsdecode(file) for file in all_files]
    #all_files = map(os.fsdecode, all_files)
    all_files = [file for file in all_files if file.lower().endswith((".jpg",".png"))]
    
    #if len(all_files) == 0:
    if not all_files:
        raise(Exception("No Files"))
    
    2019-12-25 21:38:43
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载