tkcalendar的DateEntry组件年份识别错误,19xx年被识别为20xx年
解决tkcalendar DateEntry将19xx年识别为20xx年的问题
问题根源
tkcalendar的DateEntry组件默认采用了两位数年份的解析逻辑,导致选择19xx年的日期时,被错误识别为20xx年(如1989年变为2089年)。
修复步骤
1. 显式指定DateEntry的四位数年份格式
创建DateEntry时,通过date_pattern参数明确指定包含四位数年份的格式,确保组件正确解析和显示年份:
birthDateEntry = DateEntry(root, width=12, background='darkblue', foreground='white', borderwidth=2, font=("Copperplate Gothic Light", 10), date_pattern="mm/dd/yyyy")
2. 优化日期格式化代码
使用strftime("%m/%d/%Y")直接生成四位数年份的日期字符串,无需额外替换操作:
# 获取正确的日期字符串 birth_date_str = birthDateEntry.get_date().strftime("%m/%d/%Y") student = Student(fullNameEntrada.get(), birth_date_str)
3. 修复年龄计算方法
原getAge方法依赖字符串切片,逻辑脆弱且易出错。改用datetime模块解析日期后计算年龄,确保准确性:
from datetime import date class Student(): def __init__(self, name, birthdate): self.name = name self.birthdate = birthdate self.age = self.getAge() self.registerDate = date.today().strftime("%m/%d/%Y") self.connection = sqlite3.connect('students.db') self.cursor = self.connection.cursor() self.createTable() def getAge(self): today = date.today() birth_date = date.strptime(self.birthdate, "%m/%d/%Y") age = today.year - birth_date.year # 若当年生日未过,年龄减1 if (today.month, today.day) < (birth_date.month, birth_date.day): age -= 1 return age
验证效果
修改后选择1989年5月13日时,birthDateEntry.get()会返回05/13/1989,birthDateEntry.get_date()返回1989-05-13,年龄计算也会准确无误。
内容的提问来源于stack exchange,提问作者Rodrigo Garcia Ramalho
相关产品推荐
相关产品推荐

