如何让python自动将冒号放入时间格式(HH:MM:SS)

from tkinter import *

root=Tk()

root.geometry("300x300")

def t_input():

    print(e1.get())

l1=Label(root,text="Enter here your time:")

l1.place(x=20,y=50)

e1=Entry(root,bd=2,width=25)

e1.place(x=90,y=50)

b1=Button(root,text="Enter",command=t_input)

b1.place(x=240,y=50)

root.mainloop()

这是我的代码,用户必须在小时、分钟、秒后输入冒号


请帮我把它设为默认


拉风的咖菲猫
浏览 171回答 1
1回答

饮歌长啸

在我的示例中,我们扩展了Entry小部件来处理您的时间格式。确保validatecommand我们输入的是数字,并且文本与regular expression.&nbsp;该键bind处理冒号的插入。import tkinter as tk, reclass TimeEntry(tk.Entry):&nbsp; &nbsp; def __init__(self, master, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; tk.Entry.__init__(self, master, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; vcmd = self.register(self.validate)&nbsp; &nbsp; &nbsp; &nbsp; self.bind('<Key>', self.format)&nbsp; &nbsp; &nbsp; &nbsp; self.configure(validate="all", validatecommand=(vcmd, '%P'))&nbsp; &nbsp; &nbsp; &nbsp; self.valid = re.compile('^\d{0,2}(:\d{0,2}(:\d{0,2})?)?$', re.I)&nbsp; &nbsp; def validate(self, text):&nbsp; &nbsp; &nbsp; &nbsp; if ''.join(text.split(':')).isnumeric():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return not self.valid.match(text) is None&nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; def format(self, event):&nbsp; &nbsp; &nbsp; &nbsp; if event.keysym != 'BackSpace':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i = self.index('insert')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if i in [2, 5]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if self.get()[i:i+1] != ':':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; self.insert(i, ':')class Main(tk.Tk):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; tk.Tk.__init__(self)&nbsp; &nbsp; &nbsp; &nbsp; TimeEntry(self, width=8).grid(row=0, column=0)if __name__ == "__main__":&nbsp; &nbsp; root = Main()&nbsp; &nbsp; root.geometry('800x600')&nbsp; &nbsp; root.title("Time Entry Example")&nbsp; &nbsp; root.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python