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

如何在打印新Label前删除旧Label?Tkinter日期选择问题

解决Tkinter日历选择后重复显示日期的问题

你的问题出在每次点击按钮都会新建一个Label组件,旧的组件不会自动消失。这里提供两种简洁的解决方式:

方法一:复用同一个Label(推荐)

先初始化一个空的日期显示Label,每次点击按钮时只更新它的文本内容,避免重复创建组件:

from tkinter import*
from tkcalendar import*

root=Tk()
root.title("Code project")

# 初始化空的日期显示Label
selectedDate = Label(root, text="")
selectedDate.pack()

def selectDate():
    myDate = my_Cal.get_date()
    # 直接更新已有Label的文本
    selectedDate.config(text=myDate)

my_Cal= Calendar(root, setmode='day', date_pattern='d/m/yy')
my_Cal.pack()

openCal = Button(root, text="Select Date", command=selectDate)
openCal.pack()

root.mainloop()

方法二:销毁旧Label后创建新的

如果需要每次创建新Label,可以用变量记录旧的组件实例,每次点击先销毁旧组件再创建新的:

from tkinter import*
from tkcalendar import*

root=Tk()
root.title("Code project")

# 用变量保存旧Label实例,初始为None
old_label = None

def selectDate():
    global old_label
    # 若旧Label存在则销毁
    if old_label is not None:
        old_label.destroy()
    myDate = my_Cal.get_date()
    # 创建新Label并更新记录变量
    old_label = Label(root, text=myDate)
    old_label.pack()

my_Cal= Calendar(root, setmode='day', date_pattern='d/m/yy')
my_Cal.pack()

openCal = Button(root, text="Select Date", command=selectDate)
openCal.pack()

root.mainloop()

第一种方法更高效,无需频繁销毁和重建组件,优先推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:40:57