简体   繁体   English

无法使用 Tkinter GUI 在线程中执行代码

[英]Cant get code to execute in thread with Tkinter GUI

Here is the code it is supposed to scan and enumerate a directory and make hashes of whatever files it finds and append them to a dict the code all works separately but I cant get the hashing part to trigger within the threaded code there is no error这是它应该扫描和枚举目录并对它找到的任何文件进行散列并将它们附加到字典的代码所有代码都单独工作但我无法在线程代码中触发散列部分没有错误

 import threading
 import tkinter as tk
 import tkinter.ttk as ttk
 import hashlib
 import glob


 class global_variables:
     def __init__(self):
         pass
     DirSelected = '' 
     Manifest = []

 class App(tk.Tk):
     def __init__(self):
         super().__init__()
         self.title("Progress bar example")
         self.button = tk.Button(self, text="Start", command=self.start_action)
         self.button.pack(padx=10, pady=10)

     def start_action(self):
         self.button.config(state=tk.DISABLED)

         t = threading.Thread(target=self.contar)
         t.start()

         self.windows_bar = WinProgressBar(self)

     def contar(self):

         directories_scanned = [str, 'File,Md5!']  # , separator value ! delineator adds new line
         target_dir = '/Users/kyle/PycharmProjects/' # this wont run 
         files = glob.glob(target_dir + '/**/*.*', recursive=True)  # Line adds search criteria aka find all all to the
         # directory for GLOB
         for file in files:
             with open(file, "rb") as f:
                 file_hash = hashlib.md5()
                 while chunk := f.read(8192):
                     file_hash.update(chunk)
                 directories_scanned.append(
                     file + ',' + str(file_hash.hexdigest() + '!'))  # Appends the file path and Md5
          global_variables.Manifest = directories_scanned

          for x in range(len(global_variables.DirSelected)):  # testing to view files TODO REMOVE this
             print(global_variables.DirSelected[x])
    
         for i in range(10): #to here 
             print("Is continuing", i)

         print('stop')

         self.windows_bar.progressbar.stop()
         self.windows_bar.destroy()
         self.button.config(state=tk.NORMAL)


 class WinProgressBar(tk.Toplevel):
     def __init__(self, parent):
         super().__init__(parent)
         self.title("Progress")
         self.geometry("300x200")
         self.progressbar = ttk.Progressbar(self, mode="indeterminate")
         self.progressbar.place(x=30, y=60, width=200)
         self.progressbar.start(20)


 if __name__ == "__main__":
     global_variables()
     app = App()
     app.mainloop()
     print("Code after loop")
     for x in range(len(global_variables.DirSelected)):  # testing to view files TODO REMOVE this
          print(global_variables.DirSelected[x])

No errors can be shown this time the code will run这次代码将运行,不会显示任何错误

It works fine for me.这对我来说可以。 I think you just were checking the wrong variable DirSelected which was in fact an empty string.我认为您只是检查了错误的变量DirSelected ,它实际上是一个空字符串。 (see my code) (见我的代码)

Also, I moved your WinProgressBar so it is available when the thread is executing.此外,我移动了您的WinProgressBar以便在线程执行时它可用。 (was getting an exception on this). (对此有例外)。

import threading
import tkinter as tk
import tkinter.ttk as ttk
import hashlib
import glob


class global_variables:
    def __init__(self):
        pass
    DirSelected = '' 
    Manifest = []

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Progress bar example")
        self.button = tk.Button(self, text="Start", command=self.start_action)
        self.button.pack(padx=10, pady=10)

    def start_action(self):
        self.button.config(state=tk.DISABLED)
        self.windows_bar = WinProgressBar(self)

        t = threading.Thread(target=self.contar)
        t.start()

    def contar(self):

        directories_scanned = [str, 'File,Md5!']  # , separator value ! delineator adds new line
        target_dir = '/home/jsantos/workspace/blog.santos.cloud/' # this wont run 
        files = glob.glob(target_dir + '/**/*.*', recursive=True)  # Line adds search criteria aka find all all to the
        # directory for GLOB
        for file in files:
            with open(file, "rb") as f:
                file_hash = hashlib.md5()
                while chunk := f.read(8192):
                    file_hash.update(chunk)
                directories_scanned.append(
                    file + ',' + str(file_hash.hexdigest() + '!'))  # Appends the file path and Md5
        global_variables.Manifest = directories_scanned

        for x in range(len(global_variables.Manifest)):  # testing to view files TODO REMOVE this
            print(global_variables.Manifest[x])
   
        for i in range(10): #to here 
            print("Is continuing", i)

        print('stop')

        self.windows_bar.progressbar.stop()
        self.windows_bar.destroy()
        self.button.config(state=tk.NORMAL)

class WinProgressBar(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title("Progress")
        self.geometry("300x200")
        self.progressbar = ttk.Progressbar(self, mode="indeterminate")
        self.progressbar.place(x=30, y=60, width=200)
        self.progressbar.start(20)


if __name__ == "__main__":
    global_variables()
    app = App()
    app.mainloop()
    print("Code after loop")
    for x in range(len(global_variables.Manifest)):  # testing to view files TODO REMOVE this
        print(global_variables.Manifest[x])

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

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