此示例成功允许仅输入数字,但在输入第一个字符后,它不允许您删除它。为什么会这样?
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()
答案 0 :(得分:1)
因为删除该字符会留下""
,根据您的规则,这不是可接受的条目:
>>> "" in '0123456789.-+'
True
但
>>> float("")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
float("")
ValueError: could not convert string to float: