0

我试图从 tkcalaendar 获取日期并将其传递给可以保存为类变量的函数。它在第一次按下按钮时起作用,但第二次返回“TypeError:'str' object is not callable”

from tkinter import *
from tkcalendar import *
import datetime

class test_class():
    
    selected_date = ""
    
    def __init__(self):
        self.window = Tk()
        
        self.stu_cal = Calendar(self.window,selectmode="day",year=int(test_class.get_year()),month=int(test_class.get_month()))
        self.stu_cal.grid(row=9,column=0)
        
        self.b3 = Button(self.window,text="Select this date",bg='#B6BDC4',fg='white',command=self.add_selected_date)
        self.b3.grid(row=9,column=6)
        
        self.window.mainloop()
        
    def add_selected_date(self):
        test_class.selected_date(self.stu_cal.get_date())
        
    @staticmethod    
    def get_year():
        currentDateTime = datetime.datetime.now()
        date = currentDateTime.date()
        return date.strftime("%Y")
    
    @staticmethod 
    def get_month():
        currentDateTime = datetime.datetime.now()
        date = currentDateTime.date()
        return date.strftime("%m")
    
    @classmethod
    def selected_date(cls,cal_date):
        cls.selected_date = cal_date

test_class()
4

1 回答 1

0

selected_date您为类变量和类方法使用了相同的名称。

建议将类方法重命名为set_selected_date()

class test_class():

    selected_date = ""

    def __init__(self):
        self.window = Tk()

        self.stu_cal = Calendar(self.window,selectmode="day",year=int(test_class.get_year()),month=int(test_class.get_month()))
        self.stu_cal.grid(row=9,column=0)

        self.b3 = Button(self.window,text="Select this date",bg='#B6BDC4',fg='white',command=self.add_selected_date)
        self.b3.grid(row=9,column=6)

        self.window.mainloop()

    def add_selected_date(self):
        # use new function name
        test_class.set_selected_date(self.stu_cal.get_date())

    @staticmethod
    def get_year():
        currentDateTime = datetime.datetime.now()
        date = currentDateTime.date()
        return date.strftime("%Y")

    @staticmethod
    def get_month():
        currentDateTime = datetime.datetime.now()
        date = currentDateTime.date()
        return date.strftime("%m")

    # renamed to set_selected_date
    @classmethod
    def set_selected_date(cls,cal_date):
        cls.selected_date = cal_date
于 2021-09-02T10:20:07.647 回答