从 Python Tkinter 条目小部件检查日期格式

编程入门 行业动态 更新时间:2024-10-26 01:25:58
本文介绍了从 Python Tkinter 条目小部件检查日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-30 05:37:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:条目   部件   日期   格式   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!