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

Cách tạo System Tray icon cho ứng dụng Tkinter


System Tray icon hiển thị trạng thái chạy của ứng dụng trên thanh tác vụ. Tương tự bài trước, dùng pystray và Pillow.

Cài đặt: pip install pystray

  • Import pystray, PIL.
  • Hàm hide_window() thu nhỏ cửa sổ, tạo icon tray.
  • Menu "Show" và "Quit" với hàm xử lý.

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ổ.

Cách tạo System Tray icon cho ứng dụng Tkinter

Đóng cửa sổ, icon xuất hiện trên khay hệ thống.

Cách tạo System Tray icon cho ứng dụng Tkinter