【问题标题】:Make multiple shapes work together in Zelle Graphics在 Zelle Graphics 中使多个形状协同工作
【发布时间】:2020-05-27 08:38:49
【问题描述】:

我是 Python 的初学者,我正在使用 Zelle 的图形库。我希望绘制多个形状并使它们表现得像一个。例如,我可能将一组形状称为“x”,当我使用内置的 move() 方法时,整个形状集合都会移动。

【问题讨论】:

  • 你可以使用海龟。
  • 如果您提供到目前为止所拥有的代码 sn-p,有人可能会提供解决方案。

标签: python zelle-graphics


【解决方案1】:

我设想的解决方案是一个新的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 本身并不是一个真正的图形对象,因此我们覆盖drawmove 而不是_draw_move,就像一个适当的图形实体一样。

【讨论】:

  • @AnnZen,在你把我的评论回馈给我之前,通配符导入 from graphics import * 是 Zelle Graphics 的惯用语,也是“不使用通配符导入”的罕见例外之一。而不是简短的代码示例。
  • 有趣的是,我的收件箱中从未收到过这条评论。
  • @AnnZen,我将其作为对您的一个问题的评论。 ;-)
  • 当我说 this comment 时,我指的是以 "@AnnZen,在你发表我的评论之前..."开头的那个跨度>
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多