【问题标题】:How to use turtle.onclick with an object from a class?如何将turtle.onclick与类中的对象一起使用?
【发布时间】:2021-06-19 09:46:27
【问题描述】:

我想为海龟按钮创建一个类,并有一个作为海龟的字段 这是我写的代码:

class button:
  def __init__(self,color,x,y):
     self.turtle=turtle.Turtle()
     self.turtle.penup()
     self.turtle.shape("square")
     self.turtle.color(color)
     self.turtle.speed(0)
     self.turtle.goto(x,y)

现在我想将onclick 用于按钮实例,那么我该怎么做呢?是这样的吗?

  def click(self,x,y):
     print ("hello world")
     self.turtle.onclick()

顺便说一句,我的课程不太好,所以我只想要一些简单的东西。

【问题讨论】:

    标签: python methods turtle-graphics python-turtle python-class


    【解决方案1】:

    以下是如何将类的click() 方法绑定到鼠标单击事件。请参阅turtle.onclick() 方法的文档。

    import turtle
    
    SCREENWIDTH = 640
    SCREENHEIGHT = 480
    
    class Button:
        def __init__(self,color,x,y):
            self.turtle = turtle.Turtle()
            self.turtle.penup()
            self.turtle.shape("square")
            self.turtle.color(color)
            self.turtle.speed(0)
            self.turtle.goto(x,y)
            self.turtle.onclick(self.click)  # Bind mouse-click event to method.
    
        def click(self, x, y):
            print ("hello world")
    
    
    if __name__ == "__main__":
        mainscreen = turtle.Screen()
        mainscreen.mode("standard")
        mainscreen.setup(SCREENWIDTH, SCREENHEIGHT)
        Button('red', 0, 0)
        turtle.mainloop()
    

    附:我强烈建议您阅读并开始遵循PEP 8 - Style Guide for Python Code 中的编码建议。这将使您的代码更易于阅读和理解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多