栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python

正确的答案是,使用

validatecommand
小部件的属性。不幸的是,尽管在
Tkinter
中有足够的文档记录,但该功能在
Tkinter
领域中的记录不足。即使没有很好地记录下来,它也具有验证所需的一切,而无需求助于绑定或跟踪变量,或在验证过程中修改小部件。

诀窍是要知道您可以让

Tkinter
将特殊值传递给
validate
命令。这些值为您提供了决定数据是否有效所需的所有信息:编辑之前的值,编辑之后的值(如果编辑有效)以及其他几位信息。但是,要使用这些命令,您需要做一点巫术,以使此信息传递到您的
validate
命令。

注意:验证命令返回

True
或至关重要
False
。任何其他情况都会导致该小部件的验证被关闭。

这是一个仅允许小写的示例(并显示所有这些时髦的值):

import tkinter as tk  # python 3.x# import Tkinter as tk # python 2.xclass Example(tk.frame):    def __init__(self, parent):        tk.frame.__init__(self, parent)        # valid percent substitutions (from the Tk entry man page)        # note: you only have to register the ones you need; this        # example registers them all for illustrative purposes        #        # %d = Type of action (1=insert, 0=delete, -1 for others)        # %i = index of char string to be inserted/deleted, or -1        # %P = value of the entry if the edit is allowed        # %s = value of entry prior to editing        # %S = the text string being inserted or deleted, if any        # %v = the type of validation that is currently set        # %V = the type of validation that triggered the callback        #      (key, focusin, focusout, forced)        # %W = the tk name of the widget        vcmd = (self.register(self.onValidate),     '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')        self.entry = tk.Entry(self, validate="key", validatecommand=vcmd)        self.text = tk.Text(self, height=10, width=40)        self.entry.pack(side="top", fill="x")        self.text.pack(side="bottom", fill="both", expand=True)    def onValidate(self, d, i, P, s, S, v, V, W):        self.text.delete("1.0", "end")        self.text.insert("end","OnValidate:n")        self.text.insert("end","d='%s'n" % d)        self.text.insert("end","i='%s'n" % i)        self.text.insert("end","P='%s'n" % P)        self.text.insert("end","s='%s'n" % s)        self.text.insert("end","S='%s'n" % S)        self.text.insert("end","v='%s'n" % v)        self.text.insert("end","V='%s'n" % V)        self.text.insert("end","W='%s'n" % W)        # Disallow anything but lowercase letters        if S == S.lower(): return True        else: self.bell() return Falseif __name__ == "__main__":    root = tk.Tk()    Example(root).pack(fill="both", expand=True)    root.mainloop()

有关调用该

register
方法时幕后情况的更多信息,请参见输入验证
tkinter



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/384131.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号