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

Python如何从tkcalendar库获取选中的出生日期并在界面指定位置显示

tkcalendar 获取选中日期问题修复

核心问题原因

  • 代码开头定义的cal = Calendar仅引用了Calendar类本身,不是界面上实际渲染的日历实例,无法通过它获取选中值
  • 你在__init__方法中创建的真实可用的日历实例是类属性self.cal,直接调用它的get_date()方法即可拿到选中的日期

修正方案

删除开头多余的cal = Calendar,然后取消display方法中出生日期展示部分的注释,将日期调用改为self.cal.get_date()即可。

修正后完整代码

from tkinter import *
from tkcalendar import *

root = Tk()
root.geometry("1000x1000")

class MyEntry:
    def display(self,clicked):
        global lbl1, lbl2, lbl3, lbl4,x,str1,str2,str3
        x = self.var.get()
        str1 = self.e1.get()
        str1 = 'Name  : ' + str1
        if x == 1:
            str3 = 'Gender : Male'
        if x == 2:
            str3 = 'Gender : Female'
        str2 = clicked.get()
        lbl1 = Label(text=str1).place(x=50, y=700)
        lbl2 = Label(text="Age   : " + str2).place(x=50, y=720)
        lbl3 = Label(text=str3).place(x=50, y=740)
        # 修正部分:调用实例属性self.cal的get_date方法获取日期
        lbl4 = Label(text="Date of Birth: " + self.cal.get_date())
        lbl4.place(x=50,y=760)

    def __init__(self, root):
        self.var = IntVar()
        self.f = Frame(root, height=1000, width=1000)
        self.f.propagate(0)
        self.f.pack()
        self.l1 = Label(text='Enter you name: ')
        self.l2 = Label(text='Select your age: ')
        self.l3 = Label(text='Select your gender: ')
        self.l4 = Label(text='Select your Date of Birth: ')
        self.e1 = Entry(self.f, width=25, fg='black', bg='white', font=('Ariel', 14))
        self.b1 = Radiobutton(self.f, text='Male', width=15, height=2, variable=self.var, value=1)
        self.b2 = Radiobutton(self.f, text='Female', width=15, height=2, variable=self.var, value=2)
        options = []
        for i in range(1, 101):
            options.append(i)
        clicked = StringVar()
        clicked.set("1")
        drop = OptionMenu(root, clicked, *options)
        drop.pack()
        self.cal = Calendar(self.f, font="Arial 14", selectmode='day')
        self.cal.pack(pady=20)
        self.cal.place(x=450, y=180)
        self.a = Button(self.f, text="Submit", command=lambda:self.display(clicked))
        self.a.place(x=300, y=400)
        self.l1.place(x=50, y=25)
        self.e1.place(x=450, y=25)
        self.l2.place(x=50, y=75)
        drop.place(x=450, y=75)
        self.l3.place(x=50, y=125)
        self.b1.place(x=450, y=125)
        self.b2.place(x=600, y=125)
        self.l4.place(x=50, y=175)

mb = MyEntry(root)
root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:48:03