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

如何为tkcalendar添加按钮实现选中日期背景着色?

解决tkcalendar中calevent_create和tag_config不生效的问题

你的问题出在日期格式不匹配:你通过cal.get_date()获取的是dd-mm-y格式的字符串,但calevent_create方法对字符串日期的解析依赖系统locale,直接传入字符串容易导致无法识别,进而事件创建失败,tag_config自然也看不到效果。

解决方法很简单,直接用cal.selection_get()获取选中的datetime.date对象,这个方法返回的是标准日期对象,能被calevent_create正确识别:

修改后的完整代码:

# Import Required Library
from tkinter import *
from tkcalendar import Calendar
from datetime import date

# Create Object
root = Tk()

# Set geometry
root.geometry("400x400")

# Add Calendar
cal = Calendar(root, firstweekday="monday", selectmode='day', year=2023, month=1, day=1,
               background="black", disabledbackground="black", bordercolor="white",
               headersbackground="black", normalbackground="black", foreground='white',
               normalforeground='white', headersforeground='white', date_pattern="dd-mm-y")

cal.pack(pady=20)


def grad_date():
    # 直接获取选中的datetime.date对象,避免格式问题
    dt = cal.selection_get()
    # 转换为字符串用于显示
    dt_str = dt.strftime("%d-%m-%Y")
    date.config(text="Selected Date is completed: " + dt_str)
    
    # 可选:先检查该日期是否已有标记,避免重复添加事件
    existing_events = cal.get_calevents(date=dt, tag="Message")
    if not existing_events:
        cal.calevent_create(dt, 'Task Completed', tags="Message")
        cal.tag_config("Message", background='red', foreground='yellow')


# Add Button and Label
Button(root, text="Complete Date",
       command=grad_date).pack(pady=20)

date = Label(root, text="")
date.pack(pady=20)

# Execute Tkinter
root.mainloop()

关键修改点:

  • 用cal.selection_get()替代cal.get_date(),直接获取datetime.date类型的选中日期
  • 可选添加重复标记检查,避免同一日期多次创建事件
  • 调整事件描述为更贴合需求的"Task Completed"

这样点击按钮后,选中的日期就会显示你设置的红色背景和黄色前景,实现任务完成标记的效果。

内容的提问来源于stack exchange,提问作者ale.spool

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:00:58