创建多个对象图形

时间:2016-03-26 07:15:02

标签: python python-3.x graphics

继承我的代码。我正在使用zelle的graphics.py.我的目标是创建多个对象(多个对象),但如果我要绘制超过十个对象,它会变得很难看。我只是想知道如何在不创建对象的情况下简化helper_function()中的代码?包括不同的颜色。

def main_function():
      win = GraphWin ("Example" , 1000,1000)
      win.setBackground("green")

def helper_function():
      b = Circle(Point(50,50),20)
      b.setFill("blue")
      b.draw(win)

      b = Circle(Point(50,100),20)
      b.setFill("blue")
      b.draw(win)

      b = Circle(Point(50,150),20)
      b.setFill("blue")
      b.draw(win)

      g = Circle(Point(300,50),20)
      g.setFill("green")
      g.draw(win)

      g = Circle(Point(350,50),20)
      g.setFill("green")
      g.draw(win)

      g = Circle(Point(400,50),20)
      g.setFill("green")
      g.draw(win) 

      g = Circle(Point(450,200),20)
      g.setFill("green")
      g.draw(win) 

1 个答案:

答案 0 :(得分:0)

你可以创建一个包含x,y,radius和color的元组列表并在其上循环,并将常用方法应用于如下所示的对象:

from graphics import *

def main_function():
    win = GraphWin ("Example" , 1000,1000)
    win.setBackground("green")
    circle_params = [(50, 50, 20, "blue"),
                   (50 ,100, 20, "blue"),
                   (50,100, 20, "green"),
                   (300,50, 20, "green"),
                   (350,50, 20, "green"),
                   (400,50, 20, "green"),
                   (450,50, 20, "green"),
                   ]
    helper_function(win, circle_params)

def helper_function(win, circle_params):
    for param in circle_params:
        a = Circle(Point(param[0], param[1]), param[2]).setFill(param[3]).draw(win)

或者:

 def helper_function(win, circle_params):
    circle_obj_lst = [Circle(Point(param[0], param[1]), param[2]).setFill(param[3]).draw(win) for param in circle_params]

OR

def helper_function(win, circle_params):
    circle_obj_lst = map(lambda param:Circle(Point(param[0], param[1]), param[2]).setFill(param[3]).draw(win) ,circle_params)

希望这有助于:)