尝试以下操作:
from tkinter import *
from tkinter.ttk import *
root = Tk()
text = StringVar()
text.set('100.0')
def validate(inp):
try:
float(inp)
except ValueError:
return False
return True
vcmd = root.register(validate)
a = Entry(textvariable=text,
validate='key',
validatecommand=(vcmd, '%P'))
a.pack()
b = Entry()
b.pack()
root.mainloop()
我validate='key'
改用了。
和替换validate
功能。a in b
检查a
包含在中的子字符串b
。
>>> '100.00' in '0123456789.-+'
False
>>> '100.00' in 'blah blah 100.00 blah blah'
True
选择
使用focusout
:
from tkinter import *
from tkinter.ttk import *
root = Tk()
text = StringVar()
text.set('100.0')
last_ok_value = text.get()
def validate(inp):
global last_ok_value
try:
float(inp)
except ValueError:
return False
last_ok_value = inp
return True
def invalidate():
text.set(last_ok_value)
vcmd = root.register(validate)
ivcmd = root.register(invalidate)
a = Entry(textvariable=text,
validate='focusout',
validatecommand=(vcmd, '%P'),
invalidcommand=(ivcmd,))
a.pack()
b = Entry()
b.pack()
root.mainloop()
使用类:
from tkinter import *
from tkinter.ttk import *
class FloatEntry(Entry):
def __init__(self, *args, **kwargs):
initial_value = kwargs.pop('initial_value', '100.00')
assert self.validate(initial_value), 'Invalid initial_value given'
self.last_valid_value = initial_value
self.text = StringVar(value=initial_value)
Entry.__init__(self, *args, textvariable=self.text, **kwargs)
self.vcmd = self.register(self.validate)
self.ivcmd = self.register(self.invalidate)
self['validate'] = 'focusout'
self['validatecommand'] = self.vcmd, '%P',
self['invalidcommand'] = self.ivcmd,
def validate(self, inp):
try:
float(inp)
except ValueError:
return False
self.last_valid_value = inp
return True
def invalidate(self):
self.text.set(self.last_valid_value)
root = Tk()
FloatEntry(initial_value='100.0').pack()
Entry().pack()
root.mainloop()