Tkinter GUI很冷

时间:2015-02-08 18:15:52

标签: python tkinter

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

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

经过多次尝试,当我点击我的boutton时,我仍然需要冻结GUI 所以我决定用一个主题来调用这个动作 我不知道我们是否应该这样做以避免冻结...

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

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


我的班级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'

我希望能够找到足够详细的问题来寻求帮助,谢谢

1 个答案:

答案 0 :(得分:5)

您应该尝试子类化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) 

希望它有所帮助!

相关问题