class SystemTray: #Initialises the system tray def __init__(self): #system tray image loading image = Image.open('icon.ico') image.load() #Makes a menu for the system tray icon menu = Menu( MenuItem('Start Recognition', self.onStartRecognition), MenuItem('Stop Recognition', self.onStopRecognition), MenuItem('Exit', self.exitProgram)) #Creates the icon and makes it visible self.icon = Icon(name='Speech Transcriber', title='Speech Transcriber', icon=image, menu=menu) self.icon.visible = True #Starts the system tray def startSysTray(self): self.icon.run() #Starts recognition when the start button is clicked on the menu def onStartRecognition(self, icon): self.startspeech print("start") #Stops recognition when the stop button is clicked on the menu def onStopRecognition(self, icon): print("stop") #Closes the program when the quit button is clicked in the menu def exitProgram(self, icon): self.icon.stop()
def __init__(self): #system tray image loading image = Image.open('icon.ico') image.load() #Makes a menu for the system tray icon menu = Menu( MenuItem('Start Recognition', self.onStartRecognition), MenuItem('Stop Recognition', self.onStopRecognition), MenuItem('Exit', self.exitProgram)) #Creates the icon and makes it visible self.icon = Icon(name='Speech Transcriber', title='Speech Transcriber', icon=image, menu=menu) self.icon.visible = True
def tray(): global icon, thread icon = None thread = None name = 'ED - Autopilot' icon = Icon(name=name, title=name) logo = Image.open(resource_path('src/logo.png')) icon.icon = logo icon.menu = Menu( MenuItem( 'Scan Off', set_state(0), checked=get_state(0), radio=True ), MenuItem( 'Scan on Primary Fire', set_state(1), checked=get_state(1), radio=True ), MenuItem( 'Scan on Secondary Fire', set_state(2), checked=get_state(2), radio=True ), MenuItem('Exit', lambda : exit_action()) ) keyboard.add_hotkey('home', start_action) keyboard.add_hotkey('end', stop_action) icon.run(setup)
class SysTray: """ systray icon using pystray package """ def __init__(self, main_window): self.main_window = main_window self.tray_icon_path = os.path.join(config.sett_folder, 'systray.png') # path to icon self.icon = None self._hover_text = None self.Gtk = None self.active = False def show_main_window(self, *args): self.main_window.unhide() def minimize_to_systray(self, *args): self.main_window.hide() @property def tray_icon(self): """return pillow image""" try: img = atk.create_pil_image(b64=APP_ICON, size=48) return img except Exception as e: log('systray: tray_icon', e) if config.TEST_MODE: raise e def run(self): # not supported on mac if config.operating_system == 'Darwin': log('Systray is not supported on mac yet') return options_map = {'Show': self.show_main_window, 'Minimize to Systray': self.minimize_to_systray, 'Quit': self.quit} # make our own Gtk statusIcon, since pystray failed to run icon properly on Gtk 3.0 from a thread if config.operating_system == 'Linux': try: import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk self.Gtk = Gtk # delete previous icon file (it might contains an icon file for old pyidm versions) delete_file(self.tray_icon_path) # save file to settings folder self.tray_icon.save(self.tray_icon_path, format='png') def icon_right_click(icon, button, time): menu = Gtk.Menu() for option, callback in options_map.items(): item = Gtk.MenuItem(label=option) item.connect('activate', callback) menu.append(item) menu.show_all() menu.popup(None, None, None, icon, button, time) icon = Gtk.StatusIcon() icon.set_from_file(self.tray_icon_path) icon.connect("popup-menu", icon_right_click) icon.connect('activate', self.show_main_window) self.active = True Gtk.main() return except Exception as e: log('Systray Gtk 3.0:', e, log_level=2) self.active = False # let pystray decide which backend to run try: from pystray import Icon, Menu, MenuItem items = [] for option, callback in options_map.items(): items.append(MenuItem(option, callback, default=True if option == 'Show' else False)) menu = Menu(*items) self.icon = Icon('PyIDM', self.tray_icon, menu=menu) self.active = True self.icon.run() except Exception as e: log('systray: - run() - ', e) self.active = False def shutdown(self): try: self.active = False self.icon.stop() # must be called from main thread except: pass try: # quit main, might raise (Gtk-CRITICAL **:gtk_main_quit: assertion 'main_loops != NULL' failed) # but it has no side effect and PyIDM quit normally self.Gtk.main_quit() except: pass def quit(self, *args): """callback when selecting quit from systray menu""" # thread safe call for main window close self.main_window.run_method(self.main_window.quit)
image = "./icons/no.png" elif lowest < 20: image = "./icons/empty.png" elif lowest < 40: image = "./icons/low.png" elif lowest < 60: image = "./icons/middle.png" elif lowest < 80: image = "./icons/much.png" elif lowest < 100: image = "./icons/full.png" else: image = "./icons/no.png" # Creating icon Icon(data["model"], Image.open(image), menu=menu).run() # Simple method for notification show def low_level_notification(model, percent): notifer = ToastNotifier() notifer.show_toast(model, "Your battery is going low ({}%)".format(percent), "./icons/low_n.ico", 5, True) def run(): data = get_data() connected = True cache = None cached_process = None
class TrayIcon: def __init__(self, path_to_image: Path = image_path): # Silence PIL noisy logging logging.getLogger('PIL.PngImagePlugin').setLevel(logging.INFO) logging.getLogger('PIL.Image').setLevel(logging.INFO) self.path_to_image: Path = path_to_image self.icon: Optional['Icon'] = None self._menu: Optional['Menu'] = None self.menu_items: List['MenuItem'] = [] self.active: bool = _import_success self.running: bool = False self.add_core_menu_items() @check_if_tray_is_active def add_menu_item( self, text: str = None, action: callable = None, menu_item: 'MenuItem' = None, index: int = None, **kwargs, ): """ Add a menu item byt passing its text and function, or pass a created MenuItem. Force position by sending index """ if not any(v for v in (menu_item, text)): raise ValueError(f"Either 'text' or 'menu_item' are required") menu_item = menu_item or MenuItem(text=text, action=action, **kwargs) if index is not None: self.menu_items.insert(index, menu_item) else: self.menu_items.append(menu_item) @check_if_tray_is_active def add_menu_separator(self, index: int = None): self.add_menu_item(menu_item=Menu.SEPARATOR, index=index) def add_core_menu_items(self): open_web = partial(webbrowser.open) self.add_menu_item(text=f'Flexget {__version__}', enabled=False) self.add_menu_separator() self.add_menu_item(text='Homepage', action=partial(open_web, 'https://flexget.com/')) self.add_menu_item(text='Forum', action=partial(open_web, 'https://discuss.flexget.com/')) @property def menu(self) -> 'Menu': # This is lazy loaded since we'd like to delay the menu build until the tray is requested to run if not self._menu: self._menu = Menu(*self.menu_items) return self._menu @check_if_tray_is_active def run(self): """Run the tray icon. Must be run from the main thread and is blocking""" try: logger.verbose('Starting tray icon') self.icon = Icon('Flexget', Image.open(self.path_to_image), menu=self.menu) self.running = True self.icon.run() except Exception as e: logger.warning('Could not run tray icon: {}', e) self.running = False @check_if_tray_is_active def stop(self): if not self.running: return logger.verbose('Stopping tray icon') self.icon.stop() self.running = False
scheduler.shutdown() logger.exception(str(e)) icon.visible = True menu_items = [ # MenuItem('Force Execution', lambda: os.system(exe_file)), MenuItem('Telegram Shift Push', lambda: os.system(exe_shift_push)), MenuItem('ON Calendar Sync', lambda: os.system(exe_on_cal_sync)), MenuItem('Show Scheduled Jobs', lambda: scheduler.print_jobs()), # MenuItem('AhnLab V3', on_clicked, checked=lambda item: state), MenuItem("Exit", lambda: icon.stop()), ] menu = Menu(*menu_items) icon = Icon("Kill Shits", menu=menu) icon.title = "Kill shits" icon.icon = Image.open(icon_path) # Set Event Driven Method t = threading.Thread(target=eventhook.run) t.daemon = True t.start() # Icon run logger.info("## Icon running") icon.run(setup=callback) logger.info("## Quit")