简体   繁体   中英

Python Tkinter hide and show window via hotkeys

I'm trying to write a program that I can hide and show via hotkeys. I managed to get the application to show and hide using the library "keyboard", however due to the "wait" function of the library, it prevents the Text box from functioning correctly. I have tried using the key bindings within Tkinter, however I had a different problem, whereby once the program was hidden or another application was selected, I couldn't return the focus to the hidden window via the hotkey.

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()

Any assistance would be great :)

Just drop this wait command, its an additional mainloop, which is not needed as Tkinter does its job. I tried to fix your problem with threading, but as I wanted to check exactly what is NOT working, I accidentially made what I suppose you wanted to. So the Code is:

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()

I hope this works for you. I'd also recommend changing this key settings. Testing with those in PyZo is IMPOSSIBLE! It always tries to "save as...", which I don't want to...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM