You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tkinter获取tkcalendar日期显示到Label报错缺少参数如何解决

错误原因

  • 你定义的getdate是全局函数,Tkinter按钮触发时不会自动给它传入self和cont参数,且全局函数无法直接访问StartPage类内部定义的日历控件cal和显示标签date_label
  • 你在StartPage的__init__中定义的cal、date_label都是局部变量,离开__init__方法后就无法被其他代码访问

修复步骤

  1. 删掉原来全局定义的getdate函数,将该方法移动到StartPage类内部定义,删除多余的cont参数,只保留self
  2. 将StartPage里的cal、date_label加上self.前缀,变为实例属性,方便类内方法访问
  3. 按钮的command绑定改为lambda调用类内的getdate方法
  4. 修正你代码中photo1的语法错误,补全图片路径

修复后的关键代码片段

class StartPage(tk.Frame): #创建启动页
    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        
        label = tk.Label(self, text="StudyFriendO", font = LARGE_FONT, bg="#f2fcff")
        label.pack(fill="x")

        # 替换为你自己的图片路径
        photo1 = tk.PhotoImage(file='你的图片路径.png')
        panel = tk.Label(self, image = photo1)
        panel.image = photo1
        panel.pack(fill="x")

        label2 = tk.Label(self, text="请输入今日日期和你的名字:", bg="#f2fcff")
        label2.pack(fill="x", ipady=20)

        # 日历控件加self前缀变为实例属性
        self.cal = Calendar(self, background="#e0f6fc", disabledbackground="white", bordercolor="light blue", headersbackground="light blue", normalbackground="#e0f6fc", foreground="black", normalforeground='black', headersforeground='white', selectmode="day", year=2021, month=8, day=9)
        self.cal.place(relx=0.5, rely=0.5, anchor='center')

        nameentry = tk.Entry(self, width=20, bg="white")
        nameentry.place(relx=0.5, rely=0.68, anchor='center')
        
        # 按钮绑定改为调用类内方法
        caldate = ttk.Button(self, text="提交", 
                            command=lambda: self.getdate())
        caldate.place(relx=0.5, rely=0.63, anchor='center')

        button1 = ttk.Button(self, text="进入", 
                            command=lambda: controller.show_frame(HomePage))
        button1.place(relx=0.5, rely=0.73, anchor='center')

        # 日期标签加self前缀变为实例属性
        self.date_label = tk.Label(self, text="")
        self.date_label.pack(pady=20)

        self.configure(bg='#f2fcff')
    
    # getdate作为类方法定义
    def getdate(self):
        self.date_label.config(text="今日日期是:" + self.cal.get_date())

内容的提问来源于stack exchange,提问作者Minbutt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:15:04