2

I am new to python & requesting help from experts in this community. I am trying to display the output of the following script in my Tkinter GUI. I have followed many solutions provided on the StackOverflow, but unfortunately, I am unable to implement those solutions in my code. I need help in displaying the output of the following script in my Tkinter GUI. So I can display the output in a Tkinter widget.

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

Help Required section:

  • How to display the below command output in Tkinter diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100)
  • The below command is not displaying all the result from starting to end. It is showing only the last output. Difference_per_label.config(text='diff_per ' + filename + "_&_" + templateFilename + ' saved')
  • Once it is done I want to apply try except logic for the statement corrected label i.e currently displaying as diffvalue = print("Image similarity %ge of_" + filename + "_&_" + templateFilename + "_is", score * 100) & print('diff_per ' + filename + "_&_" + templateFilename + ' saved') so that if nothing is present in the folder it will throw exception command.

Note:

  • Image similarity %ge of_: Fixed
  • filename: Variable
  • _&_: Fixed
  • templateFilename:Variable
  • _is:Fixed
  • score*100: Varies according to the difference percentage

Any help would be appreciated. Thanks in advance.

Req: Please close the answer only if all the solutions of Help Required section: is resolved.

4
  • print() only sends text on screen. It never returns displayed text. To assign to variable use it without print() - diffvalue = "Image ..." Commented Dec 18, 2019 at 8:17
  • if you want to append text to Label then you have to get old text from Label, append new text to old text, put all again to Label Commented Dec 18, 2019 at 8:19
  • BTW: we close question only if question is useless (ie. there is other question with solution, or there is not enough information to resolve it, etc.) , not when all problems are resolved. Commented Dec 18, 2019 at 8:38
  • else:continue and continue at the end of if is useless if there is no other code after conitunue in loop. Commented Dec 18, 2019 at 8:44

1 Answer 1

1

print() only sends text on screen. It never returns displayed text.
To assign to variable use it without print() - ie.

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

And now you can display text in Label or Text or Listbox


To append text to Label you have to get old text from Label, concatenate new text to old text, and put all again to Label - ie

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

or shorter wiht +=

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

Because tkinter (and other GUIs) doesn't update widget in window when you change text in label but when it ends function executed by Button and it returns to mainloop so you may have to use root.update() after changing text in Label to force mainloop() to redraw windgets in window.


To throw exception you need raise(), not try/except which is used to catch exception.

And to test if there is no file you would have to get all data from os.listdir() as list, filter list with endswith() and check if list is empty.

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"))
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot for your support. diffvalue = "Image similarity %ge of_{}_&_{}_is {}".format(filename, templateFilename, score * 100) and Difference_per_label["text"] += "\n" + new_text was very helpful from your side. Can you please help me little more with How to update widget in window? and How to test if there is no file in the directory?
I added code which check if there is no images and raise error
what widget do you want to update? To update text in Label you have Difference_per_label["text"] = .... Other widgets similar widget["variable"] = value or widget.config(variable=value). If you run it in long running function then you may need root.update() after every widget.config(variable=value). Tkinter doesn't do it automatically in running function but after function to redraw all widgeet at once and not flicker,
Thanks for your support. It was very informative. :) have a nice day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.