Tkinter GUI 冻结

Tkinter GUI is freezing

我不知道我使用的代码是否正确。我写了一个小脚本来在硬盘中找到一个文件夹:

import sys
from tkinter import *
from tkinter import ttk
import threading
import os
mGui = Tk()
mGui.geometry('450x80')
mGui.title('Copy folder')
progressbar = ttk.Progressbar(orient=HORIZONTAL, length=200, mode='determinate')
progressbar.pack(side="bottom")

xe = 'progresscache'
def handle_click():
    progressbar.start()
    def searcher():
        for root, dirs, files in os.walk(r'c:'):
            for name in dirs:
                if name == xe:
                    print ("find !")
                    progressbar.stop()          
    t = threading.Thread(target=searcher)
    t.start()

dirBut = Button(mGui, text='Go find !', command = handle_click)
dirBut.pack()
mGui.mainloop()

经过几次尝试,我仍然不得不冻结 GUI,当我点击我的按钮时。
所以我决定用线程调用动作。
我不知道我们是否应该这样做以避免冻结...

好吧,一切似乎都没有冻结..

现在,我想用我的代码做一个 class, 但每次我收到线程错误 这是我的代码:


我的 class Searcher.py(在 Appsave 文件夹中)

import os
import threading
class Searcher:

    def recherche(zeFolder):
        for root, dirs, files in os.walk(r'c:'):
            for name in dirs:
                if name == zeFolder:
                    print ("Finded !")
                    progressbar.stop()
    threading.Thread(target=recherche).start()

我的主要.py

# -*- coding: utf-8 -*-
import sys
from tkinter import *
from tkinter import ttk
import threading
import os
from Appsave.Searcher import Searcher

mGui = Tk()
mGui.geometry('450x80')
mGui.title('Djex save')
progressbar = ttk.Progressbar(orient=HORIZONTAL, length=200, mode='determinate')
progressbar.pack(side="bottom")

xe = 'progresscache'
la = Searcher
def handle_click():
    progressbar.start()
    la.recherche(xe) 
dirBut = Button(mGui, text='Go find !', command = handle_click)
dirBut.pack()
mGui.mainloop()

这里是输出错误

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\python34\lib\threading.py", line 921, in _bootstrap_inner
    self.run()
  File "C:\python34\lib\threading.py", line 869, in run
    self._target(*self._args, **self._kwargs)
TypeError: recherche() missing 1 required positional argument: 'zeFolder'

我希望我的问题有足够的细节来寻求帮助,谢谢

你应该尝试继承 Thread,像这样:

class Searcher(threading.Thread):

    def __init__(self, zeFolder, progressbar):
        super(Searcher, self).__init__()
        self.zeFolder = zeFolder
        self.progressbar = progressbar

    def run(self):
        for root, dirs, files in os.walk(r'c:'):
            for name in dirs:
                if name == self.zeFolder:
                    print ("Finded !")
                    self.progressbar.stop()

然后,这样称呼它:

xe = 'progresscache'
la = Searcher(xe, progressbar)
def handle_click():
    progressbar.start()
    la.start()

而不是:

xe = 'progresscache'
la = Searcher
def handle_click():
    progressbar.start()
    la.recherche(xe) 

希望对您有所帮助!