Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

Python Turtle screen.onkey()

I am a beginner in python and I am building a Snake game where on the key Strokes snake can be controlled. I am trying to use screen.onkey()

I wanted to know can a function in the above function can be implemented by multiple keys

screen.onkey(fun=snake.up, key="Up")

Over here can function "snake.up" can it be assigned to another key "g"? So in total snake.up function can be performed by "Up" key and as well as "g" key

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you should try to use it then you should know that you can use two different keys to run the same function.

import turtle

def test():
    print('test')

turtle.onkey(fun=test, key="Up")
turtle.onkey(fun=test, key="g")

turtle.listen()

turtle.mainloop()

The same is with onkeypress and onkeyrelease


EDIT:

But with onkey you can't get information which key was used to execute this function.
You can't also use combinations like Ctrl+g, Alt+g, Shift+g

turtle is built on top of tkinter and you would have to access Canvas and use directly bind() for this. And function has to get one value with event's information.

import turtle

def test(event):    
    print('test event:', event)
    print('test keysym:', event.keysym)
    print('test state:', event.state)
    print('test Ctrl :', bool(event.state & 4))
    print('test Shift:', bool(event.state & 1))
    print('test Alt  :', bool(event.state & 8))
    print('---')

canvas = turtle.getcanvas()
canvas.bind('<Up>', test)
canvas.bind('<g>', test)
canvas.bind('<G>', test)  # G = Shift+g
canvas.bind('<Control-g>', test)
canvas.bind('<Alt-g>', test)

turtle.listen()

turtle.mainloop()

Result:

test event: <KeyPress event state=Mod2 keysym=g keycode=42 char='g' x=545 y=339>
test keysym: g
test state: 16
test Ctrl : False
test Shift: False
test Alt  : False
---
test event: <KeyPress event state=Shift|Mod2 keysym=G keycode=42 char='G' x=545 y=339>
test keysym: G
test state: 17
test Ctrl : False
test Shift: True
test Alt  : False
---
test event: <KeyPress event state=Control|Mod2 keysym=g keycode=42 char='x07' x=545 y=339>
test keysym: g
test state: 20
test Ctrl : True
test Shift: False
test Alt  : False
---
test event: <KeyPress event state=Mod1|Mod2 keysym=g keycode=42 char='g' x=545 y=339>
test keysym: g
test state: 24
test Ctrl : False
test Shift: False
test Alt  : True
---

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...