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

如何在Python Tkinter时钟脚本中实现特定时段更改字体颜色

修改Tkinter时钟,实现特定时段变色功能

你可以通过在时间更新函数中添加时段判断逻辑,动态调整时钟标签的前景色来实现需求。以下是修改后的完整代码:

# importing whole module
from tkinter import *
from tkinter.ttk import *

# importing strftime function to retrieve system's time
from time import strftime

# creating tkinter window
root = Tk()
root.title('Clock')

# This function is used to display time on the label
def time():
    string = strftime('%H:%M:%S')
    lbl.config(text=string)
    
    # 获取当前小时和分钟,判断是否处于目标时段
    current_hour = int(strftime('%H'))
    current_min = int(strftime('%M'))
    
    # 匹配23:45到00:00的时段(包含23:45及之后、00:00到00:59)
    if (current_hour == 23 and current_min >= 45) or current_hour == 0:
        lbl.config(foreground='red')
    else:
        lbl.config(foreground='white')
    
    lbl.after(1000, time)

# Styling the label widget so that clock will look more attractive
lbl = Label(root, font=('calibri', 40, 'bold'),
            background='purple',
            foreground='white')

# Placing clock at the centre of the tkinter window
lbl.pack(anchor='center')
time()

mainloop()

关键修改说明:

  • 在time()函数中新增时间判断逻辑:通过strftime('%H')和strftime('%M')获取当前小时和分钟,判断是否处于目标时段
  • 根据判断结果动态设置标签的foreground属性:符合时段时设为亮红色,否则恢复白色
  • 每次更新时间时同步执行颜色判断,确保时段切换时颜色自动更新

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:46:02