问题描述
我想为海龟按钮创建一个类并有一个字段作为海龟 这是我写的代码:
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 中的编码建议。这将使您的代码更易于阅读和理解。