如何让Python Tkinter时间显示程序在切换标签页时始终保持屏幕可见
实现Tkinter窗口始终置顶的方法
当然有办法!Tkinter本身就提供了直接设置窗口置顶的属性,完全能满足你的需求——让时间显示窗口一直保持在屏幕最前端,就算切换其他应用也不会被遮挡。
核心实现方案
你只需要调用窗口对象的attributes()方法,设置'-topmost'参数为True即可,这个方法在Windows、macOS和Linux主流系统上都能正常工作:
import tkinter as tk from time import strftime # 创建主窗口 root = tk.Tk() root.title("始终置顶的时间显示") # 关键:设置窗口始终处于屏幕最前端 root.attributes('-topmost', True) # 配置时间显示标签 time_label = tk.Label(root, font=('calibri', 40, 'bold'), bg='black', fg='white') time_label.pack(anchor='center', padx=20, pady=15) # 更新时间的函数 def update_time(): current_time = strftime('%H:%M:%S %p') time_label.config(text=current_time) time_label.after(1000, update_time) # 每1秒更新一次 update_time() root.mainloop()
细节补充
- 如果之后需要取消置顶(比如想给程序加个置顶开关),只需要把
True改成False再调用一次方法就行:root.attributes('-topmost', False)。 - 部分系统上也可以用
wm_attributes()替代attributes(),写法是root.wm_attributes('-topmost', True),功能完全一致。 - 极少数桌面环境可能有自定义的窗口优先级规则,但绝大多数场景下这个方法都能稳定生效。
内容的提问来源于stack exchange,提问作者HAT1412
相关产品推荐
相关产品推荐

