Python 龟 screen.onkey() [英] Python Turtle screen.onkey()

查看:33
本文介绍了Python 龟 screen.onkey()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 的初学者,我正在构建一个 Snake 游戏,可以在关键笔触上控制蛇.我正在尝试使用 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")

这里可以函数"snake.up" 可以将它分配给另一个键g"吗?所以总的来说 snake.up 功能可以通过Up"来执行.键和g"键

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

推荐答案

如果您应该尝试使用它,那么您应该知道您可以使用两个不同的键来运行相同的功能.

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

onkeypressonkeyrelease

但是使用 onkey 您无法获得用于执行此功能的密钥的信息.
您也不能使用 Ctrl+gAlt+gShift+g

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 建立在 tkinter 之上,你必须访问 Canvas 并直接使用 bind()> 为此.并且函数必须通过事件信息获取一个值.

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

结果:

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

这篇关于Python 龟 screen.onkey()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆