TKinter 'after' 方法立即执行,执行后暂停 3 秒。如果我还在 CheckStatus 函数中使用“after”方法,它将进入快速循环并且永远不会到达 mainloop()。
我究竟做错了什么?文档说该函数将在暂停时间之后调用,但实际上它发生在之前。我想每秒调用一次 CheckStatus 以获取 Raspberry Pi 上的硬件输入,并让正常的主循环响应用户事件。
from tkinter import *
def DoClick(entries):
global ButCount
ButCount += 1
print("ButCount", ButCount, "TimeCount", TimeCount)
def newform(root):
L1 = Label(root, text = "test of 'after' method which seems to call before time")
L1.pack()
def CheckStatus():
global TimeCount
TimeCount += 1
print("In CheckStatus. ButCount", ButCount, "TimeCount", TimeCount)
# root.after(3000, DoTime())
root = Tk()
ButCount = 0
TimeCount = 0
if __name__ == '__main__':
FormData = newform(root)
root.bind('<Return>', (lambda event, e=FormData: fetch(e)))
b1 = Button(root, text='Click me', command=(lambda e=FormData: DoClick(e)))
b1.pack()
print("Before root.after(")
root.after(3000, CheckStatus())
print("Done root.after(")
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
您使用后不正确。考虑这行代码:
root.after(3000, CheckStatus())
Run Code Online (Sandbox Code Playgroud)
它和这个完全一样:
result = CheckStatus()
root.after(3000, result)
Run Code Online (Sandbox Code Playgroud)
看到问题了吗?after 需要一个可调用的——对函数的引用。
解决方案是传递对该函数的引用:
root.after(3000, CheckStatus)
Run Code Online (Sandbox Code Playgroud)
即使您没有询问,对于可能想知道如何传递参数的人:您也可以包含位置参数:
def example(a,b):
...
root.after(3000, example, "this is a", "this is b")
Run Code Online (Sandbox Code Playgroud)