How do you detect key presses in python?

I have tried to make a script in python that detects key presses, but imports such as Tkinter and keyboard aren't recognised.
Can anybody help?

import pygame and detect events.

Then what do I do? How do I use them?

You have multiple choices.

  • curses library for CLI apps
  • the keyboard module
  • the turtle module (not recommended)
  • pygame (not recommended unless you're making a game)
1 Like

I have imported turtle, what script do I use to detect keypress?

window = turtle.Screen()
def callback():
    print('key pressed')
window.onkeypress(callback, 'your key')

Edit: Added window.mainloop(), changed window.onkeypress to window.onkey, added window.listen(), see my post below

It's not working!

You didnt import turtle or used from turtle import *.

pip3 install keyboard should intall a library.

Doesn't work either :frowning_face:

Try pip install keyboard then.

If you're using from turtle import * it means that you don't have to prefix the library with turtle. Replace window = turtle.Screen() with window = Screen() and make sure you add that tab (I didn't add a real tab, just 2 or 4 spaces).
Also, I forgot to mention this in my previous post, but you need to add window.mainloop() for it to listen to key presses.
Edit: it's actually window.onkey not window.onkeypress, sorry for giving you the wrong code
I fixed everything wrong in the above code snippet, try it now
You need to add window.listen() too
Live demo:
Edit 3/18/2022 9:10 PM: TheProgrammer3 => programmeruser, => replit

ok, this is something I also want to do, but I don't know how to do it (I'm also learning python, so I don't know that much)

uh, what's the point of replying? I don't even know what you mean.

Same here on learning ppython

please don't necropost (also, make sure to stay on topic)