在tkinter条目中插入默认值将停止验证

2024-09-29 23:33:07 发布

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

我一直在跟踪来自here的输入框的验证。下面的代码来自答案,附加条件是如果输入的值是'Q',那么程序会将'test'加到输入值的开头。在

但是,一旦插入此值,所有验证都将退出窗口,并且条目允许使用大写值。在我的程序上进行的一些测试显示,验证命令(在本例中是OnValidate)没有被任何进一步的条目事件(key、focusin/out等)调用。在

import Tkinter as tk
class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        vcmd = (self.root.register(self.OnValidate), 
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entry = tk.Entry(self.root, validate="key", 
                              validatecommand=vcmd)
        self.entry.pack()
        self.root.mainloop()

    def OnValidate(self, d, i, P, s, S, v, V, W):
        if S == "Q":
            self.entry.insert(0,"test")
        # only allow if the string is lowercase
        return (S.lower() == S)

app=MyApp()

我这样做的原因是,我希望条目显示一个默认值,如果它的值在用户所做的任何更改之后为空。(例如,我的情况是if not P聚焦)

任何想法如何实现这一点或什么地方出了问题,以上不胜感激。在


Tags: keytestself程序ifheredef条目
2条回答

我将完全基于以下几点来回答:

The reason for me doing this is I want the Entry to display a default value if its value is left empty after any changes that are made by a user.

希望这个例子能告诉你你想要什么:

import Tkinter as tk

def analyze(event=None):
    content = entry_contents.get()
    if content == "":
        entry_contents.set("default")

lord = tk.Tk()

entry_contents = tk.StringVar()
aEntry = tk.Entry(lord, textvariable=entry_contents)
aEntry.grid()

aText = tk.Text(lord, font=("Georgia", "12"))
aText.grid()

aEntry.bind("<FocusOut>", analyze)

lord.mainloop()

或者如果control variable对你没有任何用处:

^{pr2}$

validatecommand选项仅用于验证,不用于执行其他类型的操作。你看到的行为就是记录在案的行为。在

根据official tk documentation on entry validation

... The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand.

(注意:tkinter只不过是tk的tcl实现的包装器。因此,tcl/tk文档可以作为Tkinter行为的最终指南)

相关问题 更多 >

    热门问题