一起运行 Tkinter 窗口和 PysTray 图标 [英] Running a Tkinter window and PysTray Icon together

查看:26
本文介绍了一起运行 Tkinter 窗口和 PysTray 图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building a tkinter gui project and i'm looking for ways to run a tray icon with the tkinter window.
I found Pystray library that does it, But now i'm trying to figure it out how to use this library (tray Icon) together with tkinter window,
I set it up when the user exit winodw it's only will withdraw window:
self.protocol('WM_DELETE_WINDOW', self.withdraw)
I want to bring it back with the tray icon.. anyone know how to do it?
untill now I just wrote this code so far (they're not running together but it's also fine):

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

推荐答案

我终于弄明白了,
现在我只需要将它与我的主要代码结合起来,我希望这段代码对其他人也有帮助...

Finally I figure it out,
Now I just need to combine this with my main code, I hope this code will help to other people too...

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

这篇关于一起运行 Tkinter 窗口和 PysTray 图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆