【问题标题】:Python Tkinter hide and show window via hotkeysPython Tkinter 通过热键隐藏和显示窗口
【发布时间】:2018-11-07 06:54:42
【问题描述】:

我正在尝试编写一个可以通过热键隐藏和显示的程序。我设法使用库“键盘”让应用程序显示和隐藏,但是由于库的“等待”功能,它会阻止文本框正常运行。我曾尝试在 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()

任何帮助都会很棒:)

【问题讨论】:

    标签: python tkinter hotkeys


    【解决方案1】:

    只需删除这个等待命令,它是一个额外的主循环,在 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 中进行测试是不可能的!它总是试图“另存为...”,我不想...

    【讨论】:

    • 嗨,恐怕你的代码不适合我。热键不再起作用,使用时它们似乎会使应用程序崩溃:(
    • 也许吧。我在 python 3.5 中试过,它工作得很好。你得到哪个错误?哪个 Python 版本?显然是 2.x,但是哪一个呢?然后我会尝试用线程来做......
    • 我使用的是 python 2.7。我没有收到任何错误,只是热键似乎没有让应用程序显示或隐藏,当我按下它们时,它会将应用程序置于“无响应”状态。
    • 别担心!我升级到 python 3.6,你的代码现在似乎可以工作了:) 谢谢
    • nice :-) 我应该继续尝试线程,因为这是一种挑战,还是解决了?
    猜你喜欢
    • 1970-01-01
    • 2018-05-29
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多