แอปพลิเคชัน System Tray จะสร้างอยู่บน Taskbar ตลอดเวลา เมื่อผู้ใช้ปิดแอปพลิเคชัน จะยังคงทำงานบน Taskbar เพื่อระบุแอป System Tray ให้ภาพหรือไอคอน
สร้าง System Tray icon ของแอปพลิเคชัน Tkinter ใช้โมดูล pystray ใน Python มีฟังก์ชันและเมธอดในตัวมากมายสำหรับตั้งค่า System Tray icon
ติดตั้ง pystray ด้วยคำสั่ง "pip install pystray" ใน shell หรือ command prompt
ขั้นตอนสร้าง System Tray icon:
- นำเข้าไลบรารี Pystray, Python PIL หรือ Pillow
- กำหนดฟังก์ชัน hide_window() ซ่อนหน้าต่างและให้ไอคอนบน system tray
- เพิ่มและกำหนดเมนู 2 รายการ "Show" และ "Quit"
- เพิ่ม Command ในเมนู โดยกำหนดฟังก์ชันสำหรับ 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 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()
ผลลัพธ์
รันโค้ด จะแสดงหน้าต่างแอปพลิเคชันพร้อม widgets และ elements

ปิดหน้าต่าง จะแสดงไอคอนหน้าต่างในเมนู taskbar