【问题标题】:Up arrow key not working for python turtle向上箭头键不适用于 python turtle
【发布时间】:2022-01-22 12:21:23
【问题描述】:

我已经使用了onkey左右的函数:

sc.onkey(user_left,"left")
sc.onkey(user_right,"right")

设置turtle和导入turtle后我也设置了screen:

sc=Screen()

但是当我上下使用相同格式时:

sc.onkey(user_up,"up")
sc.onkey(user_down,"down")

它什么都不做。我也有我的功能:

def user_right:
   t3.forward(5)
def user_left:
   t3.backward(5)

t3 是我的用户乌龟,它是侧面的,形状是乌龟,它的头朝右。 t3 自动设置为在代码运行时使其头部朝向右侧。对了,我导入from turtle import*

【问题讨论】:

  • 前进/后退与左/右/上/下不同。一个是相对于海龟的,另一个是相对于屏幕的。

标签: python turtle-graphics python-turtle


【解决方案1】:

我在这里看到了几个问题。首先,这不能像您声称的那样工作:

def user_right:
    t3.forward(5)
def user_left:
    t3.backward(5)

应该是:

def user_right():
    t3.forward(5)
def user_left():
    t3.backward(5)

接下来,这在标准 Python 中的 turtle 中不起作用:

sc.onkey(user_left,"left")
sc.onkey(user_right,"right")

这些键必须是 "Left""Right"。你在使用非标准的海龟实现吗? (例如 repl.it 上的那个)您展示了两个有效的事件处理程序,但没有展示两个不起作用的事件处理程序,这在尝试调试您的代码时会更有趣。

最后,您错过了对屏幕listen() 方法的调用,因此您的击键将被忽略。以下是我可能如何实现您的代码暗示的功能:

from turtle import Screen, Turtle

def user_right():
    turtle.forward(5)

def user_left():
    turtle.backward(5)

def user_up():
    turtle.sety(turtle.ycor() + 5)

def user_down():
    turtle.sety(turtle.ycor() - 5)

turtle = Turtle()
turtle.shape('turtle')

screen = Screen()

screen.onkey(user_left, 'Left')
screen.onkey(user_right, 'Right')
screen.onkey(user_up, 'Up')
screen.onkey(user_down, 'Down')

screen.listen()
screen.mainloop()

【讨论】:

  • 我在replit上,很抱歉函数错误,它不是原始代码
  • 我有一个问题,我是用from turtle import * 版本编码的,所以有什么不同吗?
  • @SuperByte,您可以修改我的示例以使用from turtle import *。但我不推荐它。标准 Python turtle 公开了两个 API,一个是 功能性,一个是 面向对象。使用我指定的import,只引入对象API并阻止功能性API。其他import 方法可以同时引入,允许混用,可能会造成误解和问题。
猜你喜欢
  • 1970-01-01
  • 2020-05-13
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2019-08-06
相关资源
最近更新 更多