-2

蟒蛇帮助

我在用户输入的网格中绘制了一系列补丁,但希望它们循环通过用户输入的一系列颜色。即用户输入'蓝色,绿色,黄色'并且补丁应该跟随该循环一次通过每一行,即如果网格是4x4,我希望填充如下所示

    1      2      3     4
1 blue   green  yellow blue
2 green  yellow blue   green
3 yellow blue   green  yellow
4 blue   green  yellow blue


def drawPatch(win, x, y, colours):
    for i in range(100, 0, -10):
        rectangle = Rectangle(Point(x + i, y + (100 - i)), Point(x, (y+100)))
        if (i % 20) == 0:
            rectangle.setFill("white")
        else:
            rectangle.setFill(colours)
        rectangle.setOutline("")
        rectangle.draw(win)
    # win.getMouse()
    # win.close()
# drawPatch(win=GraphWin("drawPatch", 100, 100), colour="red", x=0, y=0)


def drawPatchwork():

    width = int(input("Enter width: "))
    height = int(input("Enter height: "))
    colours = input("Enter your four colours: ")
    win = GraphWin("Draw Patch", width * 100, height * 100)
    for y in range(0, height * 100, 100):
        for x in range(0, width * 100, 100):
            drawPatch(win, x, y, colours)
    win.getMouse()
    win.close()

drawPatchwork()
4

1 回答 1

1

您可以使用 的算法在itertools.cycle任意数量的颜色之间循环:

from graphics import *

def cycle(iterable):
    """
    Python equivalent of C definition of cycle(), from
    https://docs.python.org/3/library/itertools.html#itertools.cycle
    """

    saved = []

    for element in iterable:
        yield element
        saved.append(element)

    while saved:
        for element in saved:
            yield element

def drawPatch(win, x, y, colour):
    for i in range(100, 0, -10):
        rectangle = Rectangle(Point(x + i, y + (100 - i)), Point(x, y + 100))
        if (i % 20) == 0:
            rectangle.setFill('white')
        else:
            rectangle.setFill(colour)
        rectangle.setOutline("")  # no outline
        rectangle.draw(win)

def drawPatchwork():

    width = int(input("Enter width: "))
    height = int(input("Enter height: "))
    colours = cycle(map(str.strip, input("Enter your colours: ").split(',')))

    win = GraphWin("Draw Patch", width * 100, height * 100)

    for y in range(0, height * 100, 100):
        for x in range(0, width * 100, 100):
            drawPatch(win, x, y, next(colours))

    win.getMouse()
    win.close()

drawPatchwork()

用法

% python3 test.py
Enter width: 4
Enter height: 4
Enter your colours: blue, green, yellow

输出

在此处输入图像描述

于 2017-11-22T00:18:39.650 回答