我在用户输入的网格中绘制了一系列补丁,但希望它们循环显示一系列颜色,这些颜色也是由用户输入的。 即,用户输入“蓝色,绿色,黄色”,并且补丁应该一次跟随每行循环,即如果网格是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()
答案 0 :(得分: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()
<强> USAGE 强>
% python3 test.py
Enter width: 4
Enter height: 4
Enter your colours: blue, green, yellow
<强>输出强>