尝试使用列表,每次通过 if 语句时,将对象附加到列表中
X.append (class (parameters))
这样,你可以通过索引轻松获取对象
例如,我有一个类使用海龟制作一个圆圈
class StateCircle(turtle.Turtle):
def __init__(self, color, x, y, name, i, aaa = True):
turtle.Turtle.__init__(self)
turtle.tracer(0,0)
self.shape('circle')
self.shapesize(2,2,2)
self.penup()
self.color(color)
self.width = WIDTH
self.speed(0)
ta = turtle.Turtle()
ta.ht()
ta.pu()
global xxx
global textcoordinates
global labelnames
ta.goto(x,y+36)
ta.write(name, font=("Arial", 8, "normal"), align="center")
self.x = x
self.y = y
self.goto(x, y)
turtle.update()
为了制作 4 个圆圈,我在 for 循环中调用它,并将圆圈对象附加到数组列表中
self.state_circles.append(StateCircle('yellow', coordx, coordy, label, i))
For 循环是:
for i in range(4) #Or any range
self.state_circles.append(StateCircle('yellow', coordx[i], coordy[i], label, i))
#Coordx and Coordy are lists that hold the coordinates of 4 different places
现在,每当我需要参考第一个圆圈,想改变颜色时,我都可以使用
self.state_circles[0].color(colorname)