【问题标题】:Why is Python Turtle listen() not working?为什么 Python Turtle listen() 不工作?
【发布时间】:2022-11-25 20:28:53
【问题描述】:

我非常,我的意思是对 Python 非常陌生(我真的什么都不知道)。我正在尝试使用 turtle 模块创建一个小游戏,并且按照教程我没有看到 listen() 函数在工作

这是我的代码 我试图创造一个可控的角色

from turtle import *

#background
Screen().bgcolor("orange")

#player

pl = Turtle()
pl.color('dodgerblue')
pl.shape('turtle')
pl.penup()

def turnleft():
    player.left(30)

turtle.listen()
onkeypress(turnleft, "Left")

speed = 1
while True:
    pl.forward(speed)

【问题讨论】:

    标签: python turtle-graphics python-turtle


    【解决方案1】:

    当您执行 from turtle import * 时,它会将所有内容导入内置命名空间,即,您可以执行以下操作:

    listen()
    

    而不是

    turtle.listen()
    

    如果你刚刚完成

    import turtle
    

    那么 turtle 包中的所有内容都可以通过 turtle 命名空间访问,即

    turtle.listen()
    

    【讨论】:

      【解决方案2】:

      你在这里有很多错误,完全正常,因为你是新手,这是变得更好的方法。

      我会“安排”一下您的代码。

      import turtle
      
      #background
      turtle.Screen().bgcolor("orange")
      
      #player
      pl = turtle.Turtle()
      pl.color('dodgerblue')
      pl.shape('turtle')
      pl.penup()
      
      def turnleft():
          pl.left(30)
      
      turtle.listen()
      turtle.onkeypress(turnleft, "Left")
      
      speed = 1
      while True:
          pl.forward(speed)
      

      首先,我建议您在谷歌中检查什么是“OOP”并检查它在 Python 上的工作方式。

      当您使用模块(在本例中为海龟)中的“函数”时,您需要先调用模块,然后再调用函数,例如:

      turtle.onkeypress(turnleft, "Left")
      # Instead
      onkeypress(turnleft,"Left")
      

      祝你的新小项目好运,继续尝试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 2015-10-12
        • 2023-04-01
        • 1970-01-01
        • 2016-05-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多