【发布时间】:2012-12-14 21:55:12
【问题描述】:
我正处于一个我无法弄清楚自己的情况。
当我使用 Entry 小部件进行用户交互时,我很难找到验证数据的正确方法。
情况:
我有两个 Entry 小部件,用户必须在其中输入两个必须是浮点数的变量。
虽然我可以运行一个只有在输入的值为浮点数时才能正常工作的程序,但如果我将其留空或输入字母会关闭 - 因此我想验证该条目是否为浮点数:
variableentry = Entry(root and so on)
variableentry.grid()
我正在使用:
variablename = float(variableentry.get())
当我:
print(type(variablename)
我收到消息:
<class 'float'>
所以我无法使用
#...
try:
if(variablename is not float):
messagebox.showerror("Error", "Incorrect parameter")
return
这显然不起作用,因为变量名属于“float”类而不是float,我尝试了不同的输入方式而不是if语句中的float - 没有任何运气。
有什么想法吗?
提前,谢谢!
最好的问候,
卡斯帕
编辑:
我找到了:
from Tkinter import *
class ValidatingEntry(Entry):
# base class for validating entry widgets
def __init__(self, master, value="", **kw):
apply(Entry.__init__, (self, master), kw)
self.__value = value
self.__variable = StringVar()
self.__variable.set(value)
self.__variable.trace("w", self.__callback)
self.config(textvariable=self.__variable)
def __callback(self, *dummy):
value = self.__variable.get()
newvalue = self.validate(value)
if newvalue is None:
self.__variable.set(self.__value)
elif newvalue != value:
self.__value = newvalue
self.__variable.set(self.newvalue)
else:
self.__value = value
def validate(self, value):
# override: return value, new value, or None if invalid
return value
来自http://effbot.org/zone/tkinter-entry-validate.htm
但是其余的代码不是在课堂上编写的(我知道这不是最佳的,但这是老师要求的)会影响上面的例子吗?我将如何使它满足我的需求?
【问题讨论】:
标签: python python-3.x tkinter