Python, Turtle Graphics, Key bindings

让人想犯罪 __ 提交于 2020-06-17 00:51:09

问题


I'm trying to figure out a way to make it to when I hold down a key the player will constantly move, or just have the player move forward constantly with just turtle graphics, (I do have pygame installed also)

import turtle
from turtle import *

#Setup Screen
wn = turtle.Screen()
wn.setup(700,700)
wn.title("white")
wn.bgcolor("black")

#Create Player
player = turtle.Turtle()
player.penup()
player.shape("triangle")
player.color("white")

def forward():
    player.forward(20)

def lef():
    player.left(90)

def forward():
    player.right(90)

onkey(forward,"Up")
onkey(left,"Left")
onkey(right,"Right")

listen()

回答1:


You can fix it simply by adding wn to start of

wn.onkey(forward, 'Up')
wn.onkey(left, 'Left')
wn.onkey(right, 'Right')

wn.listen()
wn.mainloop()

I hope this helps!




回答2:


I recommend you read this post on repeating key events and first determine whether your operating system provides key repeat and whether you can/want to adjust that and/or how to turn it off to implement your own. That link includes code to implement your own key repeat behavior in turtle.

I've reworked your code below and the keys repeat fine for me because my operating system (OSX) implements key repeat:

from turtle import Turtle, Screen

# Setup Screen
wn = Screen()
wn.setup(700, 700)
wn.title('white')
wn.bgcolor('black')

# Create Player
player = Turtle('triangle')
player.speed('fastest')
player.color('white')
player.penup()

def forward():
    player.forward(20)

def left():
    player.left(90)

def right():
    player.right(90)

wn.onkey(forward, 'Up')
wn.onkey(left, 'Left')
wn.onkey(right, 'Right')

wn.listen()
wn.mainloop()

In OSX I can control the rate (and turn it off) in the Keyboard panel of Systems Preferences. Look into what your OS provides.

Some programming notes: avoid importing the same module two different ways, this always leads to confusion. If you find you're getting interference between keyboard events at high repetition rates consider the following for all three event handlers:

def forward():
    wn.onkey(None, 'Up')  # disable event in handler
    player.forward(20)
    wn.onkey(forward, 'Up')  # reenable event


来源:https://stackoverflow.com/questions/46867731/python-turtle-graphics-key-bindings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!