【问题标题】:Tkinter after method executing immediately方法立即执行后的 Tkinter
【发布时间】:2017-12-17 04:34:56
【问题描述】:

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

【问题讨论】:

  • after() like comman=bind() 需要 callback - 这意味着没有 () 的函数名称 - 在你的代码中 root.after(3000, CheckStatus) 没有 ()

标签: python tkinter


【解决方案1】:

您使用错误后。考虑这行代码:

root.after(3000, CheckStatus())

和这个完全一样:

result = CheckStatus()
root.after(3000, result)

看到问题了吗? after 需要一个可调用的——对该函数的引用。

解决办法是给函数传递一个引用

root.after(3000, CheckStatus)

即使您没有询问,对于可能想知道如何传递参数的人:您也可以包含位置参数:

def example(a,b):
    ...
root.after(3000, example, "this is a", "this is b")

【讨论】:

  • 非常感谢!有趣的是不正确的用法改变了时间。
【解决方案2】:

您的代码中有一个错误:

root.after(3000, CheckStatus())

应该是:

root.after(3000, CheckStatus)
#                           ^^ parens removed.

传入CheckStatus() 实际上是调用函数而不是传入它的引用。

听起来您还想一遍又一遍地调用 CheckStatus。您可以通过 CheckStatus 中的递归调用来做到这一点。你已经得到了:

# root.after(3000, DoTime())

在您的代码中,CheckStatus()。也许您想将其更改为:

root.after(3000, CheckStatus)

让您进行异步检查。

此外,根据您实际尝试执行的操作,您可能希望“递归”调用是有条件的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-02
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多