【问题标题】:Python loop through coloursPython循环遍历颜色
【发布时间】:2017-11-21 18:44:12
【问题描述】:

Python 帮助

我在用户输入的网格中绘制了一系列补丁,但希望它们循环显示用户输入的一系列颜色。 即用户输入“蓝色、绿色、黄色”,并且补丁应该跟随该循环一次通过每一行,即如果网格是 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()

【问题讨论】:

  • 请正确缩进代码
  • 代码现在应该正确缩进

标签: python loops for-loop colors zelle-graphics


【解决方案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

输出

【讨论】:

  • 谢谢,但我忘了提到我正在尝试仅使用图形文件。还是谢谢!
  • @Mark.k,将cycle() 的库实现替换为本地实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
  • 2021-04-13
  • 2018-10-26
  • 2019-04-15
相关资源
最近更新 更多