如何将turtle.onclick 与类中的对象一起使用?

问题描述

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

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,y):
     print ("hello world")
     self.turtle.onclick()

顺便说一句,我不太擅长上课,所以我只是想要一些简单的东西。

解决方法

这里是如何将类的 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,y):
        print ("hello world")


if __name__ == "__main__":
    mainscreen = turtle.Screen()
    mainscreen.mode("standard")
    mainscreen.setup(SCREENWIDTH,SCREENHEIGHT)
    Button('red',0)
    turtle.mainloop()

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...