如何在键盘的帮助下移动海龟中的物体?

2024-10-03 23:20:36 发布

您现在位置:Python中文网/ 问答频道 /正文

这个代码应该使用左右箭头键将播放器向左和向右移动,但是当我尝试按箭头键时,播放器正在消失。我该怎么解决这个问题?你知道吗

代码

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

回溯(最近一次呼叫):

File "C:\Users\Harshitha.P\AppData\Local\Programs\Python\Python37\mine.py", line 34, in player.setx(x) File "C:\Users\Harshitha.P\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 1808, in setx self._goto(Vec2D(x, self._position[1])) File "C:\Users\Harshitha.P\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 3158, in _goto screen._pointlist(self.currentLineItem), File "C:\Users\Harshitha.P\AppData\Local\Programs\Python\Python37\lib\turtle.py", line 755, in _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", line 2469, in coords self.tk.call((self._w, 'coords') + args))] _tkinter.TclError: invalid command name ".!canvas"


Tags: inpyselflocallineusersappdatafile
1条回答
网友
1楼 · 发布于 2024-10-03 23:20:36

对@patel的另一种解释可能与YouTube上的“坠落的天空”视频turtorial一致,那就是让播放器自己移动,直到到达窗口的一边,或者另一边,然后停止:

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

相关问题 更多 >