最近更新于 2025-05-04 09:59
测试环境
- Windows 11 24H2
- Python 3.13.1
Python 包:
- pystray==0.19.5
- pillow==11.2.1
示例代码
Python
import tkinter
from PIL import Image
import pystray
from threading import Thread
iconPath = './icon.ico' # 图标文件路径。这里窗口标题图标和托盘图标都使用它
class MainUI(tkinter.Frame):
def __init__(self, root: tkinter.Tk=None):
super().__init__(root)
self.root = root
root.protocol('WM_DELETE_WINDOW', self.onClosing) # 绑定关闭窗口事件
self.root.withdraw() # 隐藏主窗口
self.pack()
def createWindow(self):
"""创建主界面内容"""
tkinter.Label(self, text="Hello World!").pack()
def onClosing(self):
"""关闭窗口时触发"""
self.root.withdraw() # 隐藏主窗口
class SystemTray(Thread):
def __init__(self, root: tkinter.Tk):
super().__init__(daemon=True) # 设置为守护线程
self.root = root
def showWindows(self):
"""显示主窗口"""
self.root.after(0, self.root.deiconify) # 在主线程中显示主窗口
def exitApp(self):
"""退出程序"""
self.icon.stop() # 停止托盘图标
self.root.after(0, self.root.destroy) # 在主线程中销毁主窗口
def run(self):
"""启动托盘图标"""
# 创建菜单项
menu = pystray.Menu(
pystray.MenuItem('显示窗口', self.showWindows, default=True), # 默认单机托盘图标执行显示操作
pystray.MenuItem('退出程序', self.exitApp),
)
# 加载图标
img = Image.open(iconPath)
# 创建托盘图标
self.icon = pystray.Icon('用于系统识别图标的名称', img, '简短的名称', menu)
# 启动
self.icon.run()
def main():
root = tkinter.Tk() # 创建主窗口
root.title('Tkinter 和 Pystray 结合示例') # 设置窗口标题
root.geometry('500x200') # 设置窗口大小
root.iconbitmap(iconPath) # 设置窗口图标
mainUI = MainUI(root) # 创建主界面
mainUI.createWindow()
stary = SystemTray(root) # 创建系统托盘
stary.start() # 启动系统托盘
root.mainloop() # 启动主窗口
if __name__ == "__main__":
main()
程序运行后默认隐藏窗口,可以看到托盘图标
单击托盘图标可以显示窗口
点击窗口的关闭,由于已经把关闭操作绑定为隐藏窗口,实际不会关闭窗口,只是看不到了,还是可以通过托盘图标打开。
在托盘图标上右键有两个菜单项,可以通过这里的退出程序执行退出
Python 中使用 Tkinter 和 Pystray 实现具有托盘图标的图形程序