Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Tkinter window and PysTray Icon together

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?
EDIT: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()
like image 776
Osher Avatar asked Feb 22 '19 21:02

Osher


People also ask

How do I create a system tray icon in Python?

To create a System Tray icon of a tkinter application, we can use pystray module in Python. It has many inbuilt functions and methods that can be used to configure the system tray icon of the application. To install pystray in your machine, you can type "pip install pystray" command in your shell or command prompt.

How do I close a tkinter window without ending program?

Creating an application using tkinter is easy but sometimes, it becomes difficult to close the window or the frame without closing it through the button on the title bar. In such cases, we can use the . destroy() method to close the window.


1 Answers

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()
like image 59
Osher Avatar answered Oct 24 '22 20:10

Osher