注意:我的问题标题涉及我解决问题的思维方式。
我知道这行不通,但请听我说完。
我正在开发一个 tkinter 窗口作为我们的第一个项目,我有这个 @staticmethod ,它被传递到许多其他
@staticmethod
作为 @staticmethod
@staticmethod
def parse_date(date: str) -> datetime:
'''this function converts a string representing a date to a datetime object'''
return datetime.strptime(date, r"%Y-%m-%d").date()
现在,如果用户设法传递无效日期(例如“2023-2-30”或“2023-11-31”),此函数可能会崩溃。 因为这个方法被传递到其他方法中,所以它不会爆炸很重要。
所以我想传递一个注释“错误的日期输入”并将日期重置为
today()
,我做了以下更改:
def parse_date(self, date: str) -> datetime:
'''this function converts a string representing a date to a datetime object'''
try:
return datetime.strptime(date, r"%Y-%m-%d").date()
except:
EntryWindow.show_label(self.floating_message_label,
"wrong date input! please use calendar button.",
self.buttons_frame)
return date.today()
现在我遇到的问题是
TypeError: AddEmployeeWindow.parse_date() missing 1 required positional argument: 'self'
,这是因为parse_date()
通过称为@staticmethod
传递到另一个AddEmployeeWindow.parse_date()
,并且据我所知,如果不初始化,我无法通过instancemethod
实例。
注意:
show_label
是从类EntryWindow
继承的方法,因此你可以看出我知道我不应该将self
传递给@staticmethod
。
但问题是 floating_message_label
和 buttons_frame
是实例属性,除非通过 self
才能访问,这意味着我会得到 AttributeError
。
所以我想在将每个使用 @staticmethod
的
parse_date()
转换为
instancmethod
之前检查
有没有办法传递或使用 self
我尝试使用普通的
instancemethod
来管理例外块。
但是chatgpt一直坚持我应该使用
@classmethod
,我认为这是无稽之谈,但我认为我不能使用self.handle_date_error()
或AddEmployeeWindow.handle_date_error()
来调用这个方法
@staticmethod
def parse_date(date: str) -> datetime:
'''this function converts a string representing a date to a datetime object'''
try:
return datetime.strptime(date, r"%Y-%m-%d").date()
except:
AddEmployeeWindow.handle_date_error()
@classmethod
def handle_date_error(cls):
EntryWindow.show_label(cls.floating_message_label,
"wrong date input! please use calendar button.",
cls.buttons_frame)
return date.today()
这按预期返回了
AttributeError: type object 'AddEmployeeWindow' has no attribute 'floating_message_label'
。
我尝试将
lambda
申请为:
@staticmethod
def parse_date(date: str) -> datetime:
'''this function converts a string representing a date to a datetime object'''
try:
return datetime.strptime(date, r"%Y-%m-%d").date()
except:
return lambda self: self.handle_date_error()
def handle_date_error(self):
self.show_label(self.floating_message_label,
"wrong date input! please use calendar button.",
sefl.buttons_frame)
return date.today()
但这似乎是错误的解决方案。
我该如何解决这个问题??
阅读https://ttkbootstrap.readthedocs.io/en/latest/styleguide/dateentry/#invalid-date-entry,其中解释了如何制作必须有效的经过验证的日期条目。
这与食谱的创建验证函数指南相结合应该告诉您如何构建正确的小部件
https://ttkbootstrap.readthedocs.io/en/latest/cookbook/validate-user-input/
所有代码均来自参考站点:
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
def validate_number(x) -> bool:
"""Validates that the input is a number"""
if x.isdigit():
return True
elif x == "":
return True
else:
return False
def validate_alpha(x) -> bool:
"""Validates that the input is alpha"""
if x.isdigit():
return False
elif x == "":
return True
else:
return True
# create the toplevel window
root = ttk.Window()
frame = ttk.Frame(root, padding=10)
frame.pack(fill=BOTH, expand=YES)
# register the validation callback
digit_func = root.register(validate_number)
alpha_func = root.register(validate_alpha)
# validate numeric entry
ttk.Label(frame, text="Enter a number").pack()
num_entry = ttk.Entry(frame, validate="focus", validatecommand=(digit_func, '%P'))
num_entry.pack(padx=10, pady=10, expand=True)
# validate alpha entry
ttk.Label(frame, text="Enter a letter").pack()
let_entry = ttk.Entry(frame, validate="focus", validatecommand=(alpha_func, '%P'))
let_entry.pack(padx=10, pady=10, expand=True)
root.mainloop()
您只需纠正一个验证函数,该函数可能是您的解析函数是否成功,并将其作为
validate
函数提供给您的 DateEntry
小部件的创建。