📜  screen.onkey python (1)

📅  最后修改于: 2023-12-03 15:20:01.330000             🧑  作者: Mango

screen.onkey in Python

screen.onkey is a function provided by the turtle module in Python, which allows you to assign a function to be called whenever a specific key is pressed on the keyboard.

Usage
Syntax
screen.onkey(fun, key)
screen.onkey(fun, key=None)
Parameters
  • fun: the function to be called when the specified key is pressed
  • key: the key to bind the function to. If None is passed, the function will be bound to all keys.
Example

In the following example, we bind the exit function to the Escape key:

import turtle

def exit():
    turtle.bye()

screen = turtle.Screen()
screen.onkey(exit, "Escape")
screen.listen()

turtle.done()
Notes
  • key can be any single character or one of the following predefined strings:
    • space
    • backspace
    • tab
    • return (or enter)
    • escape (or esc)
    • insert (or ins)
    • delete (or del)
    • home
    • end
    • pageup (or pu)
    • pagedown (or pd)
    • left
    • up
    • right
    • down
  • The screen.listen() function must be called before any keys can be detected by the screen.onkey function.
  • If you want to bind multiple keys to the same function, you can pass None as the key parameter, and the function will be called whenever any key is pressed.
Conclusion

In summary, screen.onkey is a useful function in the turtle module that allows you to bind a function to specific keys on the keyboard. It is easy to use and provides a lot of flexibility in handling keyboard input in your Python programs.