8

我正在构建一个 tkinter gui 项目,并且正在寻找使用 tkinter 窗口运行托盘图标的方法。
我找到了 Pystray 库,但现在我试图弄清楚如何将这个库(托盘图标)与 tkinter 窗口一起使用,
我在用户退出 winodw 时设置它,它只会退出窗口:
self.protocol('WM_DELETE_WINDOW', self.withdraw)
我想用托盘图标把它带回来..有人知道怎么做吗?
编辑:到目前为止,我只是写了这段代码(它们没有一起运行,但也很好):

from pystray import MenuItem as item
import pystray
from PIL import Image
import tkinter as tk

def quit_window(icon, item):
    icon.stop()
    #window.destroy()

def show_window(icon, item):
    icon.stop()
    #window.deiconify()

def withdraw_window(window):    
    window.withdraw()
    image = Image.open("image.ico")
    menu = (item('Quit', quit_window), item('Show', show_window))
    icon = pystray.Icon("name", image, "title", menu)
    icon.run()

def main():
    window = tk.Tk() 
    window.title("Welcome")
    window.protocol('WM_DELETE_WINDOW', lambda: withdraw_window(window))
    window.mainloop()
main()
4

1 回答 1

20

最后我弄明白了,
现在我只需要把它和我的主要代码结合起来,我希望这段代码也能对其他人有所帮助......

from pystray import MenuItem as item
import pystray
from PIL import Image
import tkinter as tk

window = tk.Tk()
window.title("Welcome")

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

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

def withdraw_window():  
    window.withdraw()
    image = Image.open("image.ico")
    menu = (item('Quit', quit_window), item('Show', show_window))
    icon = pystray.Icon("name", image, "title", menu)
    icon.run()

window.protocol('WM_DELETE_WINDOW', withdraw_window)
window.mainloop()
于 2019-02-23T11:21:31.427 回答