0

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.

Legended
  • 119
  • 1
  • 6
  • If this is just for you and not going to be used by others then AutoHotKey might be worth trying out. – JSON Brody Aug 09 '19 at 23:50
  • Possible duplicate of [Windows 7: how to bring a window to the front no matter what other window has focus?](https://stackoverflow.com/questions/6312627/windows-7-how-to-bring-a-window-to-the-front-no-matter-what-other-window-has-fo) – JSON Brody Aug 09 '19 at 23:53
  • 1
    Does this answer your question? [Tkinter main window focus](https://stackoverflow.com/questions/22751100/tkinter-main-window-focus) – null Apr 09 '21 at 18:07

0 Answers0