pythoneventskeykey-eventspyautogui

Python: How to activate an event by keypress with pyautogui?


I've installed the pyautogui package to use the .hotkey() function to trigger an event. For example: If you press the key combination "Ctrl + c" the console shall display the message "Hello world".

I tried something like this:

while True:
   if pyautogui.hotkey("ctrl", "c"):
      print("Hello World")

It's wrong I know but is there a possibility to print this message when I've pressed Ctrl and C at the same time?


Solution

  • I solved the problem myself. It seems to be you don't need the pyautogui modul at all and you only have to implement tkinter bindings like this:

    from tkinter import *
    
    root = TK()
    
    def keyevent(event):
       if event.keycode == 67:             # Check if pressed key has code 67 (character 'c')
          print("Hello World")
    
    root.bind("<Control - Key>", keyevent) # You press Ctrl and a key at the same time   
    
    root.mainloop()