从 Python Tkinter 条目小部件检查日期格式 [英] Check Date Format from a Python Tkinter entry widget

查看:44
本文介绍了从 Python Tkinter 条目小部件检查日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Tkinter 输入框,我向用户询问格式为 YYYYMMDD 的日期.我想检查日期是否以正确的格式输入,否则会出现错误框.以下函数检查整数,但只需要下一步的帮助,即日期格式.

Using a Tkinter input box, I ask a user for a date in the format YYYYMMDD. I would like to check if the date has been entered in the correct format , otherwise raise an error box. The following function checks for an integer but just need some help on the next step i.e the date format.

    def retrieve_inputBoxes():
        startdate = self.e1.get()  # gets the startdate value from input box
        enddate = self.e2.get()    # gets the enddate value from input box
        if startdate.isdigit() and enddate.isdigit():
           pass
        else:
            tkinter.messagebox.showerror('Error Message', 'Integer Please!')
            return     

推荐答案

最简单的方法可能是使用正则表达式.然而,YYYYMMDD 显然是一种不常见的格式,我发现的正则表达式很复杂.以下是匹配 YYYY-MM-DD 格式的正则表达式示例:

The easiest way would probably be to employ regex. However, YYYYMMDD is apparently an uncommon format and the regex I found was complicated. Here's an example of a regex for matching the format YYYY-MM-DD:

import re

text = input('Input a date (YYYY-MM-DD): ')
pattern = r'(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])'
match = re.search(pattern, text)
if match:
    print(match.group())
else:
    print('Wrong format')

这个正则表达式适用于 20 世纪和 21 世纪,不会关心每个月有多少天,只关心最大值是 31.

This regex will work for the twentieth and twentyfirst centuries and will not care how many days are in each month, just that the maximum is 31.

这篇关于从 Python Tkinter 条目小部件检查日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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