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

如何为基于Tkinter开发的桌面数字时钟添加自定义背景图片?

给Tkinter数字时钟添加自定义背景图片

要实现自定义背景,你只需要在现有代码里添加图片加载逻辑,把背景图作为底层容器,再调整时钟标签的显示方式就行。下面是修改后的完整代码,我标注了所有改动的地方:

from tkinter import Tk
from tkinter import Label
import time
from PIL import Image, ImageTk


root = Tk()
root.title("Klocka")
root.attributes("-topmost", 1)
root.attributes('-alpha', 1)
root.iconbitmap('klocka.ico (1).ico')

# --- 新增:加载并设置背景图片 ---
# 定义窗口尺寸(和你原来的设置一致)
window_width = 255
window_height = 50

# 替换成你的图片路径,比如'background.jpg',确保图片和代码在同一文件夹
background_img = Image.open("your_background_image.png")
# 把图片调整到和窗口一样大
background_img = background_img.resize((window_width, window_height), Image.Resampling.LANCZOS)
# 转换成Tkinter能识别的格式
tk_bg_img = ImageTk.PhotoImage(background_img)

# 创建背景标签,铺满整个窗口
bg_label = Label(root, image=tk_bg_img)
bg_label.pack(fill="both", expand=True)
# 必须保留这行,防止图片被系统回收导致不显示
bg_label.image = tk_bg_img
# --- 背景图片设置结束 ---

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

center_x = int(screen_width/3500 - window_width / 0.97)
center_y = int(screen_height/1 - window_height / 0.62)

root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')


def present_time():
    display_time = time.strftime("%I:%M:%S")
    digi_clock.config(text=display_time)
    digi_clock.after(200,present_time)

# --- 修改时钟标签的显示设置 ---
# 让窗口的黑色区域变成透明,这样时钟的黑色背景会透出下面的图片
root.wm_attributes("-transparentcolor", "black")
# 把时钟标签放在背景标签上面,而不是直接放在窗口上
digi_clock = Label(bg_label, font=("Arial",50), bg="black", fg="red")
# --- 时钟标签修改结束 ---

digi_clock.pack()

present_time()

root.mainloop()

关键修改说明:

  • 图片加载部分:替换"your_background_image.png"为你自己的图片路径,支持jpg、png等格式。resize方法会把图片缩放到和窗口一样大,确保刚好填满。
  • 背景标签:这个标签是底层容器,必须用pack(fill="both", expand=True)让它铺满窗口,还要保留bg_label.image = tk_bg_img,否则Tkinter会自动回收图片资源,导致背景不显示。
  • 时钟标签调整:把时钟的父容器改成背景标签,这样它会显示在背景图上面;通过-transparentcolor设置让黑色背景透明,完美融合到自定义背景里。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:35:51