如何使 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("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()
輸出
如果我們執行以上程式碼,它將顯示應用程式視窗,其中包含一些小部件和元素。
如果我們關閉視窗,它將在工作列選單中顯示視窗圖示。
廣告