Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้างไอคอน System Tray ของแอปพลิเคชัน Tkinter


ไอคอน System Tray ใช้แสดงสถานะการทำงานของแอปพลิเคชันบนแถบงาน โดยทั่วไปจะแสดงว่าแอปพลิเคชันไหนกำลังทำงานอยู่ ไอคอน System Tray จะมองเห็นได้บนแถบงาน

เพื่อสร้างไอคอน System Tray ของแอปพลิเคชัน Tkinter ให้ใช้โมดูล pystray ใน Python มีฟังก์ชันและเมธอดในตัวมากมายสำหรับกำหนดค่าไอคอน System Tray

ติดตั้ง pystray ด้วยคำสั่ง pip install pystray ใน shell หรือ command prompt

ขั้นตอนสร้างไอคอน System Tray:

  • นำเข้าไลบรารีที่จำเป็น - Pystray, Python PIL หรือ Pillow
  • กำหนดฟังก์ชัน hide_window() เพื่อถอนหน้าต่างและให้ไอคอนใน system tray
  • เพิ่มและกำหนดเมนู 2 รายการ: "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 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()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่าง

วิธีสร้างไอคอน System Tray ของแอปพลิเคชัน Tkinter

เมื่อปิดหน้าต่าง จะยังคงปรากฏบนแถบงานเป็นไอคอน System Tray

วิธีสร้างไอคอน System Tray ของแอปพลิเคชัน Tkinter