[英]How to add system tray to my tkinter application and avoid using lots of pywin32 code(Just on windows)?
[英]Link my Python GUI script with system tray script pywin32 (tkinter)
I've created an executable file of my GUI python script using Pyinstaller (I used tkinter as the framework, and Anaconda3, Python 3.7 and I am on Windows 10). 我已使用任務計划程序將其設置為在 Windows 啟動時自動啟動。
我被要求讓它在系統托盤中靜默運行,但不作為服務運行(因為有時它需要用戶交互)。
感謝這里非常樂於助人的用戶:
將 python 腳本放入系統托盤(Windows)的最簡單方法是什么
如何為 Windows 構建 SystemTray 應用程序?
我有一個win32py腳本,它可以創建帶有一些菜單和簡單功能的系統托盤圖標。 但是,我無法弄清楚如何將我的 tkinter GUI 腳本與此代碼鏈接。我嘗試使用 execfile().open() 執行我的腳本並使其像腳本中的普通 menu_action 一樣運行,但它不起作用。
這里的一些討論:
表明無法在系統托盤中隱藏 tkinter 框架。 但據我了解,上面的腳本獨立於此。
我發現了這個 tcl 擴展tktray ( https://core.tcl-lang.org/jenglish/gutter/packages/tktray.html ),我現在正在學習如何將它構建到 tlc 中,這不是微不足道的和我想的一樣。 但是,tktray 已有 10 年歷史,所以我不希望它與當前版本兼容。
我發現的所有其他解決方案都適用於其他編程語言、其他操作系統或使用 PyQ5。 我不想為了這個額外的功能而用wxPython或PyQ5重寫我的整個代碼,所以如果有人可以幫助我將我的 GUI 腳本與上面的 win32py 腳本鏈接起來......
在 Tkinter 中,有一些有用的功能,例如:
root.withdraw() # to hide the window
root.deiconify() # to show the window
root.protocol() # control Tk's *protocols*
root.attributes() # control Tk's attributes that are only available in Tcl
因此,當我完全使用這些功能和此腳本時,我可以創建一個腳本,當您切換選項以隱藏/顯示它時,它可以隱藏和顯示 window
(注意:我使用的是 Windows 10 版本 1909)
from tkinter import *
from systrayicon import SysTrayIcon
def bye(): root.withdraw() # on the top badge of the main window
def toggle(): root.deiconify() # in the system tray
def main():
root = Tk()
root.withdraw() # minimises the main window at first
root.title("Hello, world!")
root.protocol("WM_DELETE_WINDOW", bye) # minimise the script into the tray with the 'X' button
root.attributes('-toolwindow', True) # only shows the destroy button
text = Label("Hello, world!")
text.pack()
SysTrayIcon(open("./icon.ico", "r"), title, ('Open the main window', None, toggle), on_quit=exit) # the function exit() is predefined, no need to worry
root.mainloop()
if __name__ == '__main__':
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.