如何借助键盘在乌龟中移动对象?

时间:2019-07-14 17:51:18

标签: python turtle-graphics

应该使用此代码使用左右箭头键将播放器左右移动,但是当我尝试按箭头键时播放器消失了。我该如何解决这个问题?

代码

import turtle

wn=turtle.Screen()
wn.title("falling skies")
wn.bgcolor("pink")
wn.setup(width=800,height=600)
wn.tracer(0)

#add player
player = turtle.Turtle()
player.speed(0)
player.shape("square")
player.color("blue")
player.penup()
player.goto(0,-250)
player.direction="stop"

#functions
def go_left():
    player.direction="left"
def go_right():
    player.direction="right"

#keyboard
wn.listen()
wn.onkeypress(go_left,"Left")
wn.onkeypress(go_right,"Right")

while True:
    wn.update()
    if player.direction == "left":
        x = player.xcor()
        x -= 3
        player.setx(x)
    if player.direction == "right":
        x = player.xcor()
        x += 3
        player.setx(x)
wn.mainloop()

回溯(最近通话最近):

  

文件   “ C:\ Users \ Harshitha.P \ AppData \ Local \ Programs \ Python \ Python37 \ mine.py”,   第34行,在       player.setx(x)文件“ C:\ Users \ Harshitha.P \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ turtle.py”,   setx中的1808行       self._goto(Vec2D(x,self._position [1]))文件“ C:\ Users \ Harshitha.P \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ turtle.py”,   _goto中的第3158行       screen._pointlist(self.currentLineItem),文件“ C:\ Users \ Harshitha.P \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ turtle.py”,   _pointlist中的第755行       cl = self.cv.coords(item)文件“”,coords文件中的第1行   “ C:\ Users \ Harshitha.P \ AppData \ Local \ Programs \ Python \ Python37 \ lib \ tkinter__init __。py”,   第2469行,坐标       self.tk.call(((self._w,'coords')+ args))]   _tkinter.TclError:无效的命令名称“。!canvas”

1 个答案:

答案 0 :(得分:0)

@patel的另一种解释,可能与YouTube上的“ Falling Skies”视频教程相吻合,是让播放器自行移动直到到达窗口的一侧或另一侧,然后停止:

from turtle import Screen, Turtle

TURTLE_SIZE = 20

# functions
def go_left():
    player.direction = 'left'

def go_right():
    player.direction = 'right'

screen = Screen()
screen.setup(width=800, height=600)
screen.title("Falling Skies")
screen.bgcolor('pink')
screen.tracer(0)

# Add player
player = Turtle()
player.shape('square')
player.speed('fastest')
player.color('blue')
player.penup()
player.sety(-250)
player.direction = 'stop'

# Keyboard
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')
screen.listen()

while True:
    x = player.xcor()

    if player.direction == 'left':
        if x > TURTLE_SIZE - 400:
            x -= 3
            player.setx(x)
        else:
            player.direction = 'stop'
    elif player.direction == 'right':
        if x < 400 - TURTLE_SIZE:
            x += 3
            player.setx(x)
        else:
            player.direction = 'stop'

    screen.update()

screen.mainloop()  # never reached