Bawer
Bawer

Reputation: 109

Check if a specific key is pressed in tkinter

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()

Upvotes: 6

Views: 10015

Answers (3)

J&#233;r&#244;me B
J&#233;r&#244;me B

Reputation: 427

If you want to catch only the 'b' on the keyboard you could also simply use root.bind("<b>", fun) in order than root.bind("<Key>", fun)

If I rewrite your code it give this :

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):
    pyautogui.moveTo(x=500, y=500)

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

Upvotes: 0

JacksonPro
JacksonPro

Reputation: 3275

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()

Upvotes: 11

Jigsaw
Jigsaw

Reputation: 320

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')

Upvotes: -1

Related Questions