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

Python Tkinter日历开发:如何从字典提取特定日程信息?

解决Tkinter日历工具的日程存储与提取问题

存储结构选择:单个字典足够

不需要用两个字典,用单个字典就能满足需求:

  • 键:直接用tkcalendar的get_date()返回的日期字符串(注意格式要和组件设置的一致,比如12/02/2023)
  • 值:用列表存储该日期下的所有日程,支持一个日期添加多条日程,避免覆盖原有内容

修正核心代码

下面是调整后的简化代码,修复了保存和显示函数的逻辑问题:

import tkinter as tk
from tkcalendar import Calendar

# 初始化日程字典:键=日期字符串,值=日程列表
schedule_dict = {}

def save_schedule():
    selected_date = cal.get_date()
    schedule_content = entry_schedule.get().strip()
    
    if schedule_content:
        # 日期已存在则追加日程,否则新建列表存储
        if selected_date in schedule_dict:
            schedule_dict[selected_date].append(schedule_content)
        else:
            schedule_dict[selected_date] = [schedule_content]
        entry_schedule.delete(0, tk.END)  # 清空输入框

def show_schedule():
    selected_date = cal.get_date()
    text_display.delete(1.0, tk.END)  # 清空显示区域
    
    # 提取并展示对应日期的日程
    if selected_date in schedule_dict:
        for idx, item in enumerate(schedule_dict[selected_date], 1):
            text_display.insert(tk.END, f"{idx}. {item}\n")
    else:
        text_display.insert(tk.END, "该日期暂无日程")

# 构建UI
root = tk.Tk()
root.title("日历日程工具")

# 统一日期格式,确保get_date()返回的字符串格式稳定
cal = Calendar(root, selectmode="day", date_pattern="dd/mm/yyyy")
cal.pack(pady=10)

entry_schedule = tk.Entry(root, width=40)
entry_schedule.pack(pady=5)

btn_save = tk.Button(root, text="保存日程", command=save_schedule)
btn_save.pack(pady=5)

btn_show = tk.Button(root, text="显示当日日程", command=show_schedule)
btn_show.pack(pady=5)

text_display = tk.Text(root, width=40, height=10)
text_display.pack(pady=10)

root.mainloop()

关键修复点说明

  1. 日期格式一致性:通过Calendar的date_pattern参数固定日期格式,保证get_date()返回的字符串能作为字典的有效键,避免因格式不匹配导致的查找失败。
  2. 多日程存储逻辑:用列表作为字典值,解决单日期多日程的存储问题,不会覆盖已有内容。
  3. 显示逻辑修正:先检查目标日期是否存在于字典中,存在则遍历列表展示所有日程,不存在则给出明确提示。

额外提示

  • 如果需要关闭程序后保留日程,可以用json模块将字典写入本地文件,启动时再读取加载。
  • 可扩展日程删除功能:通过索引或内容匹配,从对应日期的列表中移除指定日程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 21:30:42