Python Tkinter hide and show window via hotkeys

匆匆过客 提交于 2019-12-11 18:17:01

问题


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


回答1:


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


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

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


if __name__ == "__main__":
    root = Tk.Tk()
    root.geometry("800x600")
    app = MyApp(root)
    root.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...



来源:https://stackoverflow.com/questions/50570446/python-tkinter-hide-and-show-window-via-hotkeys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!