我设想的解决方案是一个新的GraphicsObject,它实际上是一组图形对象。下面是一个框架示例,其中包含足够的代码来演示这个想法:
from graphics import *
class GraphicsGroup(GraphicsObject):
def __init__(self):
super().__init__(options=[])
self.components = []
def draw(self, graphwin):
for component in self.components:
component.draw(graphwin)
return self
def move(self, dx, dy):
for component in self.components:
component.move(dx, dy)
def add_component(self, component):
if isinstance(component, GraphicsObject):
self.components.append(component)
win = GraphWin("Group Test", 200, 200)
# Some example objects borrowed from graphics.py source docstrings
text = Text(Point(35, 35), "Centered Text")
polygon = Polygon(Point(10, 10), Point(50, 30), Point(20, 70))
circle = Circle(Point(50, 50), 10)
rectangle = Rectangle(Point(25, 60), Point(60, 25))
group = GraphicsGroup()
group.add_component(text)
group.add_component(polygon)
group.add_component(circle)
group.add_component(rectangle)
group.draw(win)
win.getMouse() # Pause to view result
group.move(100, 100)
win.getMouse() # Pause to view result
win.close()
由于GraphicsGroup 本身并不是一个真正的图形对象,因此我们覆盖draw 和move 而不是_draw 和_move,就像一个适当的图形实体一样。