Python TkInter:如何在方法完成后等待回调
使用Tkinter.after方法时,代码将继续传递,而不等待回调完成Python TkInter:如何在方法完成后等待回调,python,tkinter,Python,Tkinter,使用Tkinter.after方法时,代码将继续传递,而不等待回调完成 import tkinter as tk import tkinter.ttk as ttk import time from datetime import datetime global i i = 0 global j j = 0 def SomeFunction(): global i for num in range(10): i+=1 x = barVar.ge
import tkinter as tk
import tkinter.ttk as ttk
import time
from datetime import datetime
global i
i = 0
global j
j = 0
def SomeFunction():
global i
for num in range(10):
i+=1
x = barVar.get()
barVar.set(x+5)
histrun_mainWindow.update()
time.sleep(2)
def SecondFunction():
global j
for num in range(10):
j+=1
x = barVar.get()
barVar.set(x+5)
histrun_mainWindow.update()
time.sleep(2)
def Load(run_date):
histrun_mainWindow.after(50, SomeFunction)
histrun_mainWindow.after(50, SecondFunction)
global i, j
print 'Number is :', i + j
histrun_mainWindow = tk.Tk()
run_date = datetime.today().date()
barVar = tk.DoubleVar()
barVar.set(0)
bar = ttk.Progressbar(histrun_mainWindow, length=200, style='black.Horizontal.TProgressbar', variable=barVar, mode='determinate')
bar.grid(row=1, column=0)
button= tk.Button(histrun_mainWindow, text='Run for this date ' + str(run_date), command=lambda:Load(run_date))
button.grid(row=0, column=0)
histrun_mainWindow.mainloop()
这个例子展示了正在发生的事情。.after()调用Load()函数,但不等待Load()完成,它直接进入下一行
我希望打印为10,但由于.after()不等待Load()完成其添加,所以打印为0
进度条将继续更新,以便在打印后在后台继续加载时知道已调用加载
问题:进度条不会更新-窗口将冻结,直到所有功能完成
使用线程
防止主循环
冻结您的函数-
SomeFunction
,SecondFunction
-也可以位于global
命名空间中。然后必须将
self.pbar
作为参数传递,例如SomeFunction(pbar):。。。f(self.pbar)
注意:
您会看到一个运行时错误:主线程不在主循环中 如果在
线程运行时销毁App()
窗口
输出:
SomeFunction(0)
SomeFunction(1)
SomeFunction(2)
SomeFunction(3)
SomeFunction(4)
SecondFunction(0)
SecondFunction(1)
SecondFunction(2)
SecondFunction(3)
SecondFunction(4)
Number is :8
使用Python:3.5测试
*)无法使用Python 2.7进行测试为什么需要使用
after()
延迟调用SomeFunction()
-如果直接调用它,它将按照您的意愿运行。在我的实际代码中,函数Load()
包含多个after()
方法来收集数据。每个函数都取决于已完成的前一个函数,以便它们可以使用它调用/计算的数据。我在我的示例中添加了更多的细节来说明问题。如果我在没有after()
的情况下直接调用函数,则进度条不会更新-窗口将冻结,直到所有函数都完成。也许有更好的方法获得此功能?@JK:“获得此功能的更好方法”:阅读。@stovfl感谢您的链接。不过,我很难理解它,我只习惯于非常基本的多线程,而且我以前从未使用过类。我是否需要为SomeFunction()
和SecondFunction()
创建一个单独的类,以及调用函数时如何调用类?非常感谢您的帮助!我能够使用它,并通过self.pbar
参数在线程化时打开更多的用途
SomeFunction(0)
SomeFunction(1)
SomeFunction(2)
SomeFunction(3)
SomeFunction(4)
SecondFunction(0)
SecondFunction(1)
SecondFunction(2)
SecondFunction(3)
SecondFunction(4)
Number is :8