1 回答
TA贡献1951条经验 获得超3个赞
在我的示例中,我们扩展了Entry
小部件来处理您的时间格式。确保validatecommand
我们输入的是数字,并且文本与regular expression
. 该键bind
处理冒号的插入。
import tkinter as tk, re
class TimeEntry(tk.Entry):
def __init__(self, master, **kwargs):
tk.Entry.__init__(self, master, **kwargs)
vcmd = self.register(self.validate)
self.bind('<Key>', self.format)
self.configure(validate="all", validatecommand=(vcmd, '%P'))
self.valid = re.compile('^\d{0,2}(:\d{0,2}(:\d{0,2})?)?$', re.I)
def validate(self, text):
if ''.join(text.split(':')).isnumeric():
return not self.valid.match(text) is None
return False
def format(self, event):
if event.keysym != 'BackSpace':
i = self.index('insert')
if i in [2, 5]:
if self.get()[i:i+1] != ':':
self.insert(i, ':')
class Main(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
TimeEntry(self, width=8).grid(row=0, column=0)
if __name__ == "__main__":
root = Main()
root.geometry('800x600')
root.title("Time Entry Example")
root.mainloop()
添加回答
举报