3

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?

3
  • Just supply "None", or omit the parameter altogether. Commented Apr 11, 2021 at 5:41
  • @TimRoberts, onkey() will generate errors if you supply None or omit the parameter. See @rdas answer about onkeypress(), or my answer for an explanation. Commented Apr 12, 2021 at 4:22
  • I tried this... Commented Apr 13, 2021 at 13:46

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.