Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách tạo ứng dụng System Tray (khay hệ thống) với Tkinter


Ứng dụng System Tray chạy ngầm trên thanh tác vụ khi cửa sổ chính bị đóng. Để tạo icon system tray trong Tkinter, dùng module pystray kết hợp Pillow (PIL).

Cài đặt: pip install pystray

  • Import pystray, PIL.
  • Định nghĩa hàm hide_window() thu nhỏ cửa sổ và hiện icon tray.
  • Tạo menu items "Show" và "Quit" với hàm xử lý tương ứng.

Ví dụ minh họa

from tkinter import *
from pystray import MenuItem as item
import pystray
from PIL import Image, ImageTk

win = Tk()
win.title("System Tray Application")
win.geometry("700x350")

def quit_window(icon, item):
    icon.stop()
    win.destroy()

def show_window(icon, item):
    icon.stop()
    win.after(0, win.deiconify)

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()

Kết quả đầu ra

Chạy code hiển thị cửa sổ ứng dụng.

Cách tạo ứng dụng System Tray (khay hệ thống) với Tkinter

Đóng cửa sổ, ứng dụng vẫn chạy ngầm trên khay hệ thống.

Cách tạo ứng dụng System Tray (khay hệ thống) với Tkinter