尝试使用图形创建对角线图案

时间:2019-01-01 20:56:31

标签: python graphics

我正在尝试使用图形创建对角线图案,但仅填充了一半图案。我也正在尝试使同一图案填充整个500x500,但不知道如何。 编辑:对不起,我不是全部填充,例如(0-100,500)具有线条图案,然后(100-200,500)为空等等。

from graphics import *

def patchwork():
    win = GraphWin('Lines test',500,500)
    for x in range(0,101,20):
        line = Line(Point(x,0), Point(100,100-x))
        line.setFill('red')
        line.draw(win)

     for x2 in range(101,0,-20):
        line2 = Line(Point(100,0+x2), Point(x2,100))
        line2.setFill('red')
        line2.draw(win)

我希望图案会用对角线完全填充100x100,但只有一部分会被填充。

1 个答案:

答案 0 :(得分:1)

您可以通过在单个for循环内绘制四组线来完成此操作,如下所示。该代码是根据窗口大小L编写的,因此可以根据需要轻松更改。

from graphics import *

def patchwork():
    L = 500;
    win = GraphWin('Lines test',L,L)
    for s in range(0,L+1,20):
        line1 = Line(Point(s,0), Point(L,L-s))
        line1.setFill('red')
        line1.draw(win)

        line2 = Line(Point(L,s), Point(s,L))
        line2.setFill('red')
        line2.draw(win)

        line3 = Line(Point(s,L), Point(0,L-s))
        line3.setFill('red')
        line3.draw(win)

        line4 = Line(Point(0,s), Point(s,0))
        line4.setFill('red')
        line4.draw(win)

更新代码以生成分段模式:

from graphics import *

def patchwork():
    L = 500;
    W = 100;
    f = L/W;
    win = GraphWin('Lines test',L,L)
    for xL in [0,200,400]:
      xR = xL + W;
      for s in range(0,W+1,20):
          line1 = Line(Point(xL + s,0), Point(xL,f*s))
          line1.setFill('red')
          line1.draw(win)

          line2 = Line(Point(xL + s,0), Point(xR,L - f*s))
          line2.setFill('red')
          line2.draw(win)

          line3 = Line(Point(xL + s,L), Point(xL,L - f*s))
          line3.setFill('red')
          line3.draw(win)

          line4 = Line(Point(xL + s,L), Point(xR,f*s))
          line4.setFill('red')
          line4.draw(win)