Setting tkinter to always be the current active window

放肆的年华 提交于 2021-01-29 22:26:07

问题


I'm trying to use tkinter as a way to toggle an automation process. The snippet I have below works, but the hotkeys will only work when the tkinter window is the current active window.

I found this topic discussing how this can be done, but these methods seem to be OS specific and none seem to work for Windows 10.

import tkinter as tk


class Automate(tk.Frame):

    __loop__ = None

    def __init__(self, master):
        super(Automate, self).__init__(master)

        # F7 initiates the loop.
        self.master.bind('<F7>', lambda event: self.automate())
        # F8 stops the loop.
        self.master.bind('<F8>', lambda event: self.automate_cancel())
        # F9 closes the script.
        self.master.bind('<F9>', lambda event: self.master.quit())

    def automate(self):
        """Loops over this method."""
        print('Do Stuff')
        self.__loop__ = self.master.after(1, self.automate)

    def automate_cancel(self):
        """Exits loop and reset variable."""
        print('Stop Doing Stuff')
        self.master.after_cancel(self.__loop__)
        self.__loop__ = None


if __name__ == '__main__':
    root = tk.Tk()

    # Removes Window Border, minimize button, full screen button, and exit button.
    root.overrideredirect(True)
    # Forces window to always be on top.
    root.wm_attributes('-topmost', 1)
    # Sets window as one pixel on the screen.
    root.geometry('0x0')

    Automate(root)
    root.mainloop()

In the script above, pressing F7 initiates a script and loops it. F8 stops the loop and F9 exits the program completely. The keybinds only work when tkinter is the current active window. I would like for tkinter to read my keybinds without having to open the tkinter window.

来源:https://stackoverflow.com/questions/57438200/setting-tkinter-to-always-be-the-current-active-window

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