Python Tkinter通过热键隐藏和显示窗口 [英] Python Tkinter hide and show window via hotkeys
问题描述
我正在尝试编写一个可以通过热键隐藏和显示的程序.我设法使用库键盘"来显示和隐藏应用程序,但是由于库的等待"功能,它阻止了文本"框正常运行.我曾尝试在Tkinter中使用键绑定,但是我遇到了另一个问题,即一旦隐藏了程序或选择了另一个应用程序,我就无法通过热键将焦点返回到隐藏的窗口.
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()
任何帮助都会很棒:)
推荐答案
只需删除此等待命令,它就是一个附加的主循环,因为Tkinter会执行其工作,因此不需要.我试图通过线程来解决您的问题,但是由于我想检查一下到底什么不起作用,所以我意外地做了我想您想要的事情.所以代码是:
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()
我希望这对您有用.我也建议更改此关键设置.用PyZo中的那些进行测试是不可能的!它总是尝试另存为...",我不想...
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...
这篇关于Python Tkinter通过热键隐藏和显示窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!