Python 限制Tkinter条目小部件中的值:为什么可以';我不能删除第一个字符吗?
本例成功地只允许输入数字,但在输入第一个字符后,不允许删除它。为什么会这样Python 限制Tkinter条目小部件中的值:为什么可以';我不能删除第一个字符吗?,python,validation,tkinter,Python,Validation,Tkinter,本例成功地只允许输入数字,但在输入第一个字符后,不允许删除它。为什么会这样 import Tkinter as tk class window2: def __init__(self, master1): self.panel2 = tk.Frame(master1) self.panel2.grid() self.button2 = tk.Button(self.panel2, text = "Quit", command = self
import Tkinter as tk
class window2:
def __init__(self, master1):
self.panel2 = tk.Frame(master1)
self.panel2.grid()
self.button2 = tk.Button(self.panel2, text = "Quit", command = self.panel2.quit)
self.button2.grid()
vcmd = (master1.register(self.validate),
'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
self.text1 = tk.Entry(self.panel2, validate = 'key', validatecommand = vcmd)
self.text1.grid()
self.text1.focus()
def validate(self, action, index, value_if_allowed,
prior_value, text, validation_type, trigger_type, widget_name):
if text in '0123456789.-+':
try:
float(value_if_allowed)
return True
except ValueError:
return False
else:
return False
root1 = tk.Tk()
window2(root1)
root1.mainloop()
因为删除字符会给您留下
“
,根据您的规则,这是不可接受的条目:
>>> "" in '0123456789.-+'
True
但是
>>浮点(“”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
浮动(“”)
ValueError:无法将字符串转换为浮点:
>>> float("")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
float("")
ValueError: could not convert string to float: