【问题标题】:How to move an object in turtle with the help of keyboard?如何在键盘的帮助下移动乌龟中的物体?
【发布时间】:2019-11-23 13:39:38
【问题描述】:

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

代码

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", 第 1808 行,在 setx 中 self._goto(Vec2D(x, self._position[1])) 文件“C:\Users\Harshitha.P\AppData\Local\Programs\Python\Python37\lib\turtle.py”, 第 3158 行,在 _goto screen._pointlist(self.currentLineItem),文件“C:\Users\Harshitha.P\AppData\Local\Programs\Python\Python37\lib\turtle.py”, 第 755 行,在 _pointlist 中 cl = self.cv.coords(item) File "", line 1, in coords File "C:\Users\Harshitha.P\AppData\Local\Programs\Python\Python37\lib\tkinter__init__.py", 第 2469 行,坐标 self.tk.call((self._w, 'coords') + args))] _tkinter.TclError: 无效的命令名“.!canvas”

【问题讨论】:

  • 我不相信上面的回溯与问题有任何关系。这段代码以无限循环结束,因此跳出它总是会产生某种痕迹,直到无限循环被计时器事件替换。

标签: python turtle-graphics


【解决方案1】:

@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 2021-08-29
    • 2023-04-06
    • 2022-10-15
    相关资源
    最近更新 更多