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

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


แอปพลิเคชัน System Tray สร้างขึ้นเพื่อการทำงานต่อเนื่องของโปรแกรม เมื่อผู้ใช้ปิดแอปพลิเคชัน จะยังคงทำงานบนแถบงาน (taskbar) ในการระบุแอปพลิเคชัน 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