簡體   English   中英

Python Tkinter 通過熱鍵隱藏和顯示窗口

[英]Python Tkinter hide and show window via hotkeys

我正在嘗試編寫一個可以通過熱鍵隱藏和顯示的程序。 我設法使用庫“鍵盤”使應用程序顯示和隱藏,但是由於庫的“等待”功能,它阻止了文本框正常運行。 我曾嘗試在 Tkinter 中使用鍵綁定,但是我遇到了一個不同的問題,即一旦隱藏程序或選擇了另一個應用程序,我就無法通過熱鍵將焦點返回到隱藏窗口。

import Tkinter as Tk
import keyboard

class MyApp(object):

    def __init__(self, parent):
        self.root = parent
        self.root.title("Main frame")

        self.frame = Tk.Frame(parent)
        self.frame.pack()

        self.editor = Tk.Text(self.frame)
        self.editor.pack()
        self.editor.config(font="Courier 12")
        self.editor.focus_set()


        keyboard.add_hotkey('ctrl+alt+s', self.show)
        keyboard.add_hotkey('ctrl+alt+h', self.hide)
        keyboard.wait()

        self.root.withdraw() 


    def show(self):
        self.root.update()
        self.root.deiconify()

    def hide(self):
        self.root.withdraw()


if __name__ == "__main__":
    root = Tk.Tk()
    root.geometry("800x600")
    app = MyApp(root)
    root.mainloop()

任何幫助都會很棒:)

只需刪除這個等待命令,它是一個額外的主循環,它在 Tkinter 完成其工作時不需要。 我試圖用線程解決你的問題,但因為我想確切地檢查什么不起作用,我不小心做了我想你想要的。 所以代碼是:

import tkinter as tk
import keyboard

class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.geometry("800x600")
        self.title("Main frame")

        self.editor = Tk.Text(self)
        self.editor.pack()
        self.editor.config(font="Courier 12")
        self.editor.focus_set()


        keyboard.add_hotkey('ctrl+alt+s', self.show)
        keyboard.add_hotkey('ctrl+alt+h', self.hide)


    def show(self):
        self.update()
        self.deiconify()

    def hide(self):
        self.update()
        self.withdraw()


if __name__ == "__main__":
    App().mainloop()

我希望這對你有用。 我還建議更改此鍵設置。 在 PyZo 中進行測試是不可能的! 它總是試圖“另存為...”,我不想...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM