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

如何在Tkinter数字时钟中设置背景图并让时钟显示在背景上方

解决数字时钟叠加在背景图上方的问题

原代码中canvas.pack()后再调用digi_clock.pack(),tkinter会按垂直顺序排列组件,导致时钟显示在图片下方(而非叠加在上方)。要实现时钟叠加在背景图上,有两种简单的修改方式:

方案一:使用place()定位时钟

将时钟的pack()改为place(),通过调整x和y坐标让时钟覆盖在背景图的指定位置,同时确保时钟在Canvas之后创建(tkinter中后创建的组件层级更高,会显示在上方)。

修改后的完整代码:

from tkinter import *
from PIL import ImageTk,Image
import time

root=Tk()
root.title("Klocka")
root.attributes("-topmost", 1)
root.iconbitmap('klocka.ico (1).ico')
root.geometry('300x200+50+50')

canvas=Canvas(root,width=300,height=140)
image=ImageTk.PhotoImage(Image.open("C:\\Users\\frass\\Desktop\\python projekt\\strand123.png"))
canvas.create_image(0,0,anchor=NW,image=image)
canvas.pack()

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

# 使用place定位时钟,可自行调整x、y值到合适位置
digi_clock = Label(root, font=("Times New Roman",50), activebackground="white", fg="black")
digi_clock.place(x=20, y=30)

present_time()

root.mainloop()

方案二:将时钟嵌入Canvas中

利用Canvas的create_window()方法,把时钟作为窗口组件添加到Canvas上,这样时钟会直接叠加在背景图上。

修改后的完整代码:

from tkinter import *
from PIL import ImageTk,Image
import time

root=Tk()
root.title("Klocka")
root.attributes("-topmost", 1)
root.iconbitmap('klocka.ico (1).ico')
root.geometry('300x200+50+50')

canvas=Canvas(root,width=300,height=140)
image=ImageTk.PhotoImage(Image.open("C:\\Users\\frass\\Desktop\\python projekt\\strand123.png"))
canvas.create_image(0,0,anchor=NW,image=image)

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

digi_clock = Label(canvas, font=("Times New Roman",50), activebackground="white", fg="black")
# 将时钟添加到Canvas的指定位置,anchor=NW表示以左上角为锚点
canvas.create_window(20, 30, anchor=NW, window=digi_clock)

canvas.pack()
present_time()

root.mainloop()

内容的提问来源于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.13 03:01:08