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.