我认为问题在于,耗时的循环阻止了
tkinter事件循环的
mainloop()运行。换句话说,当您的工作量大的功能与GUI在同一线程中运行时,它将占用解释器,从而干扰了它。
为防止这种情况,您可以使用辅助线程来运行函数,并在主线程中运行GUI及其进度栏。为了让您了解如何执行此 *** 作,这是一个简单的示例,我是从另一个(不相关的)进度栏问题中的代码派生的,以说明可以轻松完成类似的事情。 注意: 通常建议不要让辅助线程直接访问主线程的
tkinter对象。
from Tkinter import *import ttkimport timeimport threadingdef foo(): time.sleep(5) # simulate some workdef start_foo_thread(event): global foo_thread foo_thread = threading.Thread(target=foo) foo_thread.daemon = True progressbar.start() foo_thread.start() root.after(20, check_foo_thread)def check_foo_thread(): if foo_thread.is_alive(): root.after(20, check_foo_thread) else: progressbar.stop()root = Tk()mainframe = ttk.frame(root, padding="3 3 12 12")mainframe.grid(column=0, row=0, sticky=(N, W, E, S))mainframe.columnconfigure(0, weight=1)mainframe.rowconfigure(0, weight=1)progressbar = ttk.Progressbar(mainframe, mode='indeterminate')progressbar.grid(column=1, row=100, sticky=W)ttk.Button(mainframe, text="Check",command=lambda:start_foo_thread(None)).grid(column=1, row=200,sticky=E)for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)root.bind('<Return>', start_foo_thread)root.mainloop()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)