I want to make a program that starts from tray icon. But while making the program I found that there is no way without starting from window.mainloop()
, since I could not search any method that start from icon.run()
, and it caused lots of error, for example, the window is not on main thread blahblah
.
So My code became like this :
from pystray import MenuItem as item
import pystray
from PIL import Image
import tkinter as tk
from tkinter import ttk
from threading import Thread
import sys
import os
window = tk.Tk()
window.title("Welcome")
class trayRun():
def __init__(self,main):
self.main = main
self.image = Image.open("logo.png")
self.menu = (item('Quit', self.quit_window), item('Show', self.show_window))
self.icon = pystray.Icon("name", self.image, "title", self.menu)
self.main.protocol('WM_DELETE_WINDOW', self.withdraw_window)
self.buttonOK = ttk.Button(self.main, text='OK', command=self.ok,
width=100)
self.buttonClose = ttk.Button(self.main, text='Close window', command=self.withdraw_window,
width=100)
self.buttonOK.pack(side=tk.BOTTOM)
self.buttonClose.pack(side=tk.BOTTOM)
self.isTray = False
self.run_icon()
print(self.main)
print(self.icon)
print('------------------------')
def ok(self):
print('OKOK')
def quit_window(self):
print('quit_window')
os._exit(1)
self.icon.stop()
self.main.destroy()
print('quit')
def show_window(self):
print('show_window')
print(self.main)
#self.icon.stop()
self.main.deiconify()
print('Here?')
def withdraw_window(self):
print('withdraw_window')
self.main.withdraw()
def run_icon(self):
if self.isTray ==False:
self.icon.run_detached()
self.isTray = True
trayRun = trayRun(main=window)
window.mainloop()
It is the best code that runs without error or lack(the lack has occured when I first clicked 'Show' button to open window). What now I am thinking is this : if there is any way to automatically hide the window, is it possible to start this program without showing the window at least at user's sight ?
Please tell me that I am thinking right or there is any method to accomplish my goal .
You can use iconify() to start the program with the icon on the icon bar, but with the window minimized. Then just click on the icon when your want to see the window. Here is the simplest example:
import tkinter as tk
root = tk.Tk()
root.iconify()
root.mainloop()