gpt4 book ai didi

python - 在自己的观察者回调中修改 tkinter 变量

转载 作者:太空狗 更新时间:2023-10-30 02:53:40 25 4
gpt4 key购买 nike

我想我不太明白 tkinter 变量何时会通知观察者,何时不会。特别是,我不明白为什么下面的示例只调用一次 f:

from tkinter import Tk, IntVar

Tk()

x = IntVar()

def f(*_):
print("f called")
x.set(1)

x.trace("w", f)
x.set(0)
print(x.get())

我希望它要么在一遍又一遍地打印 f called 时永远没有响应,要么在某个时候抛出异常。相反,它只打印一次 f called,打印 1 并退出。

最佳答案

每当值更改时都会调用回调,除了在该回调中更改时。回调运行时禁用跟踪以防止无休止的递归循环。

这在规范的 tcl/tk 文档中有描述,在 trace man page 中.以下是一个简短的片段。在此上下文中,commandPrefix 指的是您的回调:

While commandPrefix is executing during a read or write trace, traces on the variable are temporarily disabled. This means that reads and writes invoked by commandPrefix will occur directly, without invoking commandPrefix (or any other traces) again. However, if commandPrefix unsets the variable then unset traces will be invoked.

关于python - 在自己的观察者回调中修改 tkinter 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48695131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com