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

Python Tkinter日历应用:每日名言重复显示异常求助

问题解决:Tkinter日历应用每日名言重复显示异常

问题现象

使用Python Tkinter开发日历应用,已实现用户输入保存至对应日期的功能。添加“每日名言”按钮后,要求同一日期始终显示同一名言,但再次点击同一日期时,无法显示之前的名言,仅显示.!Toplevel。

错误原因

核心问题在于代码中将Toplevel窗口对象存入了Quotes_dict字典,而非名言文本内容:

  • 首次生成名言时,执行Quotes_dict[datum] = Quotes_fenster,把弹窗对象作为值存入字典
  • 再次点击同一日期时,从字典取出的是窗口对象,转换为字符串就会显示.!Toplevel这类Tkinter控件的默认标识

修正方案

将Quotes_dict存储的内容改为名言文本,而非窗口对象,同时简化逻辑判断:

修正后的完整代码

from tkinter import *
from tkcalendar import *
import datetime
import secrets

root = Tk()
Quotes_dict = {}  # 存储日期对应的名言文本,而非窗口对象

today = datetime.date.today()
cal = Calendar(root, selectmode="day", year=today.year, month=today.month, day=today.day)
cal.place(x=0, y=0, height=600, width=1500)

quote_list = ['Hi', 'HI2']  # 避免与内置list类型重名


def get_random_quote(quotes):
    return secrets.choice(quotes)


def show_quote():
    Quotes_fenster = Toplevel(root)
    app_width = 1000
    app_height = 100
    Quotes_fenster.geometry(f'{app_width}x{app_height}+{125}+{10}')
    Quotes_fenster.resizable(False, False)
    Quotes_fenster.title("Zitate")

    Quotes_zitat = Label(Quotes_fenster, text="", font=18)
    Quotes_zitat.pack()

    datum = str(cal.get_date())
    if datum in Quotes_dict:
        # 日期已有记录,直接显示名言
        Quotes_zitat.config(text=Quotes_dict[datum])
    else:
        # 生成新名言并存储文本
        quote_of_the_day = get_random_quote(quote_list)
        Quotes_dict[datum] = quote_of_the_day
        Quotes_zitat.config(text=quote_of_the_day)

button = Button(root, text="Quotes", command=show_quote)
button.pack()
root.mainloop()

关键修改点

  1. 存储内容修正:将Quotes_dict[datum] = Quotes_fenster改为Quotes_dict[datum] = quote_of_the_day,确保字典存储的是名言文本
  2. 逻辑简化:用if datum in Quotes_dict:替代try-except,直接判断日期是否存在记录,代码更直观
  3. 命名优化:将list改为quote_list、random改为get_random_quote,避免与Python内置类型/函数冲突,提升代码可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:40:18