Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python turtle: trigger function on any key pressed

How can I add random key pressed with turtle (that means that I don't want this:scr.onkey(fun,'r')?

I tried this...

import turtle as system

scr=system.Screen()

def p():
     print('button pressed')

scr.onkey(p,any)

...but this does not work. How can I fix this?

like image 308
George Avatar asked Oct 15 '26 05:10

George


2 Answers

Here's a complete example -- note that you were also not showing the listen() method in your code fragment which is also required:

from turtle import Screen, Turtle

def handler():
    turtle.write("Button pressed!", align='center', font=('Arial', 18, 'normal'))

screen = Screen()

turtle = Turtle()
turtle.hideturtle()

screen.onkeypress(handler)

screen.listen()
screen.exitonclick()

Here's the story: The onkey() method is also known as onkeyrelease() and neither accepts None as a character, nor a missing character argument. @TimRoberts comment won't work. As @rdas notes (+1), use the onkeypress() method which does accept a None character, or simply a missing argument, and does what you want.

But here's a catch: Your event handler will trigger on any key, but you've no means within Turtle to determine which key. If you need that functionality, look at this answer which provides a replacement onkeypress() method that passes the character typed to your event handler, in the case where a character was not specified. (I.e. the None case.)

like image 167
cdlane Avatar answered Oct 16 '26 18:10

cdlane


You can use onkeypress instead.

scr.onkeypress(p)

The key argument, if not given, will trigger the function for any key press.

Bind fun to key-press event of key if key is given, or to any key-press-event if no key is given.

like image 39
rdas Avatar answered Oct 16 '26 20:10

rdas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!