我正在使用tkinter制作一个GUI,我分配给按钮的这个功能导致我的tkinter应用程序冻结,我无法使用其他按钮。有什么想法吗?
def open_file():
browse_text.set("loading...")
path_to_watch = filedialog.askdirectory()
print('Your folder path is"',path_to_watch,'"')
old = os.listdir(path_to_watch)
print(old)
while True:
new = os.listdir(path_to_watch)
if len(new) > len(old):
newfile = list(set(new) - set(old))
newfile = str(newfile)
newfile = newfile[2:36]
print(newfile)
global newpath
newpath = os.path.join(str(path_to_watch), newfile)#do i need an argument for filetype?
old = new
else:
continue
你的东西崩溃的问题是因为你有一个while循环。为什么?因为root.mainloop()
将永远循环,并且不能同时运行2个while循环。但是,您可以线程化这些循环或使用root.after()
函数。
1.使用threading.Thread
线程允许您一次运行多个正在运行的进程。这样做:
import threading
def open_file():
browse_text.set("loading...")
path_to_watch = filedialog.askdirectory()
print('Your folder path is"',path_to_watch,'"')
old = os.listdir(path_to_watch)
print(old)
def your_loop():
while True:
new = os.listdir(path_to_watch)
if len(new) > len(old):
newfile = list(set(new) - set(old))
newfile = str(newfile)
newfile = newfile[2:36]
print(newfile)
global newpath
newpath = os.path.join(str(path_to_watch), newfile)
old = new
else:
continue
threading.Thread(target=your_loop).start()
基本上,我们将整个while循环放在函数your_loop
上,然后使用threading.Thread
调用它
2.使用root.after()
解决这个问题的另一种方法是使用我更喜欢使用的root.after()
方法。使用它的一个优点是,我们可以为while循环提供小的中断,这样它就不会一直运行。基本上,您可以告诉root运行特定命令的内容和时间。所以你基本上可以通过这样做多次重复你的功能:
def open_file():
browse_text.set("loading...")
path_to_watch = filedialog.askdirectory()
print('Your folder path is"',path_to_watch,'"')
old = os.listdir(path_to_watch)
print(old)
def your_loop():
# No while loops? Because we are repeating the function your_loop forever!
new = os.listdir(path_to_watch)
if len(new) > len(old):
newfile = list(set(new) - set(old))
newfile = str(newfile)
newfile = newfile[2:36]
print(newfile)
global newpath
newpath = os.path.join(str(path_to_watch), newfile)
old = new
root.after(100, your_loop) # After 100 milliseconds run the function 'your_loop'
your_loop() # Running the function for the first time
希望这能解决你的问题