【问题标题】:Show output of Python script in Tkinter GUI在 Tkinter GUI 中显示 Python 脚本的输出
【发布时间】:2020-04-10 17:24:14
【问题描述】:

我是 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 ..."
  • 如果你想将文本附加到Label,那么你必须从Label获取旧文本,将新文本附加到旧文本,再将所有文本添加到Label
  • 顺便说一句:我们仅在问题无用时才关闭问题(即有其他问题有解决方案,或者没有足够的信息来解决它等),而不是在所有问题都解决后。
  • else:continuecontinueif 的末尾如果在循环中conitunue 之后没有其他代码是没有用的。

标签: python opencv user-interface image-processing tkinter


【解决方案1】:

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(和其他 GUI)在您更改标签中的文本时不会更新窗口中的小部件,但是当它结束由 Button 执行的函数并返回到主循环时,您可能必须在更改文本后使用 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"))

【讨论】:

  • 非常感谢您的支持。 diffvalue = "Image similarity %ge of_{}_&_{}_is {}".format(filename, templateFilename, score * 100)Difference_per_label["text"] += "\n" + new_text 对你很有帮助。你能帮我多一点如何更新窗口中的小部件?如何测试目录中是否没有文件?
  • 我添加了检查是否没有图像并引发错误的代码
  • 您要更新什么小部件?要更新标签中的文本,您有Difference_per_label["text"] = ...。其他类似 widget["variable"] = valuewidget.config(variable=value) 的小部件。如果您在长时间运行的函数中运行它,那么您可能需要在每个 widget.config(variable=value) 之后使用 root.update()。 Tkinter 不会在运行函数中自动执行此操作,而是在一次重绘所有小部件且不闪烁的函数之后,
  • 感谢您的支持。这是非常有用的。 :) 祝你有美好的一天。
猜你喜欢
  • 1970-01-01
  • 2017-12-29
  • 2019-08-12
  • 2018-08-05
  • 1970-01-01
  • 2020-09-21
  • 2021-03-23
  • 1970-01-01
相关资源
最近更新 更多