2

So, I've been trying to use tkinter to check if a specific key is pressed, but I haven't found anything, so I'm sarting to wonder if it's impossible. So, I'm checking if anyone knows a way to do it. By the way, I don't want to use the listener thing from pynput because it can't run simultaneously with tkinter.

If you know a way to do it and you can do in a beginner friendly way, I would appricate it alot, but if you can't, post is anyway, I'm thankfull for everyting :)

My finished script (this was what i wanted to do):

import tkinter
import pyautogui

root = tkinter.Tk()
root.geometry("1000x500")

def sum():
    label = tkinter.Label(root, text="yes")
    label.place(x=500, y=250)

def fun(event):
    if event.keysym=='b':
        pyautogui.moveTo(x=500, y=500)

root.bind("<Key>", fun)
root.mainloop()
Bawer
  • 69
  • 1
  • 8

2 Answers2

6

Bind KeyRelease or Key to a function. The function will be called with an argument when the event occurs. The argument will contain all the information about the event.

Sample output:

<KeyPress event state=Mod1|Mod3 keysym=d keycode=68 char='d' x=85 y=111>

now to get the key use event.keysym

sample program:

from tkinter import *

def fun(event):
    print(event.keysym, event.keysym=='a')
    print(event)

root = Tk()

root.bind("<KeyRelease>", fun)
root.mainloop()

JacksonPro
  • 3,135
  • 2
  • 6
  • 29
0

You could try using the keyboard library to check if any keyboard input is incoming. Here is some example code:

import keyboard

# Check if b was pressed
if keyboard.is_pressed('b'):
    print('b Key was pressed')
Jigsaw
  • 294
  • 1
  • 3
  • 14