繁体   English   中英

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

[英]Show output of Python script in Tkinter GUI

我是 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()

需要帮助部分:

  • 如何在 Tkinter 中显示以下命令输出diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100)
  • 下面的命令没有显示从开始到结束的所有结果。 它只显示最后一个输出。 Difference_per_label.config(text='diff_per ' + filename + "_&_" + templateFilename + ' saved')
  • 完成后,我想应用try except语句更正标签的逻辑,即当前显示为diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100) & print('diff_per ' + filename + "_&_" + templateFilename + ' saved')这样如果文件夹中没有任何内容,它将抛出异常命令。

笔记:

  • 图像相似度 %ge of_ : 固定
  • 文件名:变量
  • _&_ : 固定
  • 模板文件名:变量
  • _is : 固定
  • score*100 : 根据差异百分比变化

任何帮助,将不胜感激。 提前致谢。

要求:只有在“需要帮助”部分的所有解决方案都已解决时,请关闭答案。

print()只在屏幕上发送文本。 它永远不会返回显示的文本。 要分配给变量使用它而不使用print() - 即。

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

现在您可以在LabelTextListbox显示文本


要将文本附加到Label您必须从Label获取旧文本,将新文本连接到旧文本,然后再次将所有文本放入Label - 即

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

或更短的+=

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

因为tkinter (和其他图形用户界面),当您在标签更改文本,但是当它结束时通过功能按键执行不窗口小部件更新,并返回到主循环,所以你可能需要使用root.update()在标签更改文本后强制mainloop()在窗口中重绘小窗。


要抛出异常,您需要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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM