对tk.Entry textvariable调用tk.StringVar.set()会导致validate=“focusout”停止被调用

2024-05-15 14:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

问题在标题中,本质上是:在设置条目的textvariable之后,如何让validatecommand回调继续被调用?以下是最小工作示例(MWE):

import tkinter as tk

root = tk.Tk()
sv = tk.StringVar()


def callback():
    print(sv.get())
    sv.set('Set Text.')
    return True


e = tk.Entry(root, textvariable=sv, validate="focusout",                 
             validatecommand=callback)
e.grid()
e = tk.Entry(root)
e.grid()
root.mainloop()

注意,第二个tk.Entry小部件允许第一个小部件失去焦点,这是我们试图捕获的事件

现在的代码是这样的,当您运行它时,您可以更改top Entry小部件的文本一次。它将正确地设置为Set Text.,然后,如果您再次尝试更改条目的文本,新文本将在小部件中,但是回调不会发生

另一方面,如果注释掉sv.set('Set Text.')代码,此行为将完全消失,回调将被调用任意多次

How can I have the sv.set() functionality, while still maintaining the callback getting called every time the Entry widget loses focus?


Tags: thetext文本目的部件callbackroottk
1条回答
网友
1楼 · 发布于 2024-05-15 14:18:24

这将在Tk manual page for ^{}中讨论:

The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand. Such editions will override the one that was being validated.

可以推测,这样做是为了避免无限递归

您可以运行这个(而不是给定的Tcl代码,after idle {%W config -validate %v}

root.after_idle(lambda: e.config(validate="focusout"))

从回调中计划重新配置小部件以再次启用验证(在更改源之后,使e是正确的Entry小部件,即不是第二个)

相关问题 更多 >