削减程序中的代码并使之更整洁

时间:2019-01-08 02:30:12

标签: python python-3.x zelle-graphics

我很难剪切代码并将其放入循环中,以便使程序代码更加整洁。

尽管我的代码可以像预期的那样工作,但我认为有一种正确的创建方法,可以添加for循环而不是编写所有这些代码,但是我知道有一个简单的方法可以做到这一点,想不到如何正确地做。我知道我想创建一个for循环。

正方形

from graphics import *

def main():
    win = GraphWin("Squares", 500, 500)


    rect = Rectangle(Point(0,500), Point(500,0))
    rect.setFill("Red")
    rect.draw(win)

    rect2 = Rectangle(Point(20,480), Point(480,20))
    rect2.setFill("white")
    rect2.draw(win)

    rect3 = Rectangle(Point(40,460), Point(460,40))
    rect3.setFill("red")
    rect3.draw(win)

    rect4 = Rectangle(Point(60,440), Point(440,60))
    rect4.setFill("white")
    rect4.draw(win)

    rect5 = Rectangle(Point(80,420), Point(420,80))
    rect5.setFill("red")
    rect5.draw(win)

    rect6 = Rectangle(Point(100,400), Point(400,100))
    rect6.setFill("white")
    rect6.draw(win)

    rect7 = Rectangle(Point(120,380), Point(380,120))
    rect7.setFill("red")
    rect7.draw(win)

    rect8 = Rectangle(Point(140,360), Point(360,140))
    rect8.setFill("white")
    rect8.draw(win)

    rect9 = Rectangle(Point(160,340), Point(340,160))
    rect9.setFill("red")
    rect9.draw(win)

    rect10 = Rectangle(Point(180,320), Point(320,180))
    rect10.setFill("white")
    rect10.draw(win)

    rect11 = Rectangle(Point(200,300), Point(300,200))
    rect11.setFill("red")
    rect11.draw(win)

    rect12 = Rectangle(Point(220,280), Point(280,220))
    rect12.setFill("white")
    rect12.draw(win)

结果显示正方形拼凑而成

enter image description here

3 个答案:

答案 0 :(得分:0)

尝试以下操作:

from graphics import *

def main():
    win = GraphWin("Squares", 500, 500)

    # create all rects
    rects = [Rectangle(Point(0 + 20*i,500 - 20*i), Point(500 - 20*i, 0 + 20*i)) for i in range(12)]

    # draw all rects
    for idx, rect in enumerate(rects):
        rect.fill("red" if idx % 2 == 0 else "white")
        rect.draw(win)

答案 1 :(得分:0)

如果拼凑而成的只是背景,并且您不打算对其进行修改,则可以使用以下方法:

from graphics import *

def main():
    win = GraphWin("Squares", 500, 500)

    i = 1
    for x in range(0, 221, 20):
        rect = Rectangle(Point(x, 500 - x), Point(500 - x,x))
        rect.setFill("red" if i % 2 else "white")
        rect.draw(win)
        i += 1

答案 2 :(得分:0)

一种替代方法,由于使用矩形的轮廓作为 other 颜色,因此只需要绘制一半的矩形即可:

ojdbc7

它已完全参数化,因此您可以通过调整SQUARE, WIDTH = 500, 20 def main(): win = GraphWin("Squares", SQUARE, SQUARE) save_config = dict(DEFAULT_CONFIG) DEFAULT_CONFIG.update(dict(outline='red', fill='white', width=WIDTH)) for xy in range(WIDTH//2, SQUARE//2, WIDTH*2): Rectangle(Point(xy, SQUARE - xy), Point(SQUARE - xy, xy)).draw(win) DEFAULT_CONFIG.update(save_config) SQUARE参数使其适合不同尺寸的正方形或具有不同宽度的条纹。使用当前设置的参数,而不是用交替的颜色绘制12个矩形,而是绘制6个带有红色轮廓的白色矩形:

enter image description here