如何让python自动将冒号放入时间格式(HH:MM:SS) [英] How to make python automatically put colon in the format of time (HH:MM:SS)

查看:38
本文介绍了如何让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()

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

This is my code, the user has to input a colon after hour, minute, seconds

请帮我把它设为默认

推荐答案

在我的示例中,我们扩展了 Entry 小部件来处理您的时间格式.validatecommand 确保我们输入的是数字,并且文本与 正则表达式 匹配.键 bind 处理冒号的插入.

In my example we extend the Entry widget to handle your time format. The validatecommand makes sure we are inputting numbers, and that the text matches the regular expression. The key bind handles insertion of colon.

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()

这篇关于如何让python自动将冒号放入时间格式(HH:MM:SS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆