如何在Tkinter中创建系统托盘应用程序?
系统托盘应用程序是为了程序的持续运行而创建的。当用户关闭应用程序时,它将继续在任务栏上运行。为了识别系统托盘应用程序,我们可以为其应用程序提供图像或图标。
要创建Tkinter应用程序的系统托盘图标,我们可以在Python中使用pystray模块。它有很多内置函数和方法,可用于配置应用程序的系统托盘图标。
要在您的机器上安装pystray,您可以在shell或命令提示符中键入“**pip install pystray**”命令。
要创建系统托盘图标,您可以按照以下步骤操作:
导入所需的库 - **Pystray**、Python **PIL** 或 **Pillow**。
定义一个函数**hide_window()**来隐藏窗口并将图标添加到系统托盘。
添加并定义两个菜单项,“**显示**”和“**退出**”。
通过为“显示”和“退出”定义函数来在菜单项中添加命令。
示例
# Import the required libraries
from tkinter import *
from pystray import MenuItem as item
import pystray
from PIL import Image, ImageTk
# Create an instance of tkinter frame or window
win=Tk()
win.title("System Tray Application")
# Set the size of the window
win.geometry("700x350")
# Define a function for quit the window
def quit_window(icon, item):
icon.stop()
win.destroy()
# Define a function to show the window again
def show_window(icon, item):
icon.stop()
win.after(0,win.deiconify())
# Hide the window and show on the system taskbar
def hide_window():
win.withdraw()
image=Image.open("favicon.ico")
menu=(item('Quit', quit_window), item('Show', show_window))
icon=pystray.Icon("name", image, "My System Tray Icon", menu)
icon.run()
win.protocol('WM_DELETE_WINDOW', hide_window)
win.mainloop()输出
如果您运行以上代码,它将显示应用程序窗口。
如果我们关闭窗口,它仍然会作为系统托盘应用程序出现在任务栏中。

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP