pythontkinter

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

Solution

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