如何使Tkinter窗口出现在任务栏中?
系统托盘应用程序始终在任务栏上创建。当用户关闭应用程序时,它会在任务栏上运行。为了识别系统托盘应用程序,我们可以为其应用程序提供图像或图标。
要创建Tkinter应用程序的系统托盘图标,可以使用Python中的 pystray 模块。它有许多内置的函数和方法,可以用来配置应用程序的系统托盘图标。
要在计算机上安装 pystray ,您可以在您的shell或命令提示符中键入 “pip install pystray” 命令。
要创建系统托盘图标,可以按照以下步骤操作 –
- 导入所需的库- Pystray, Python PIL 或 Pillow。
-
定义一个函数 hide_window() 来撤回窗口并向系统托盘提供图标。
-
添加并定义两个菜单项 “Show” 和 “Quit” 。
-
通过为 Show 和 Quit 定义函数,向菜单项中添加命令。
示例
# 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 quitting 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("image.ico")
menu=(item('Quit', quit_window), item('Show', show_window))
icon=pystray.Icon("name", image, "title", menu)
icon.run()
win.protocol('WM_DELETE_WINDOW', hide_window)
win.mainloop()
输出
如果我们运行上述代码,它将显示带有一些小部件和元素的应用程序窗口。
如果我们关闭窗口,则会在任务栏菜单中显示窗口图标。