简体   繁体   English

为什么我在 python 中的方形绘图函数没有向下移动一行?

[英]Why does my square drawing function in python not shift down a row?

from graphics import *

def patch2():
    win = GraphWin("pattern", 100,100)
    TLX = 0
    TLY = 0
    BRX = 20
    BRY = 20
    for i in range(5):
        for i in range(5):
            r = Rectangle(Point(TLX,TLY), Point(BRX,BRY))
            r.draw(win)
            BRX += 20
            TLX += 20
            print(BRY)
        BRY = BRY + 20
        TLY = TLY + 20

patch2()

the purpose of the code is to draw 25 boxes (5x5).代码的目的是绘制 25 个框 (5x5)。 The second for loop works, and draws 5 boxes across the top row of the graphics window, but it doesn't do the other 4 rows.第二个 for 循环有效,并在图形窗口的顶行绘制 5 个框,但它不会执行其他 4 行。 TL AND BR stand for top left and bottom right (x and y coordinates) TL AND BR 代表左上角和右下角(x 和 y 坐标)

Simply adding TLX = 0 after the inner for loop fixes the drawing but also resetting BRX = 20 fixes the code.在内部for循环修复绘图后简单地添加TLX = 0 ,但也重置BRX = 20修复代码。 We can simplify things a bit by tossing the BR* variables:我们可以通过抛出BR*变量来简化一些事情:

from graphics import *

def patch2():
    tl_x, tl_y = 0, 0

    for _ in range(5):
        for _ in range(5):
            r = Rectangle(Point(tl_x, tl_y), Point(tl_x + 20, tl_y + 20))
            r.draw(win)
            tl_x += 20

        tl_x = 0
        tl_y += 20

win = GraphWin("pattern", 100, 100)

patch2()

Or, we can make use of the Point classes inherited methods and make the design more point-oriented:或者,我们可以利用Point类继承的方法,使设计更加面向点:

from graphics import *

def patch2():
    top_left = Point(0, 0)
    bottom_right = Point(20, 20)

    for _ in range(5):
        for _ in range(5):
            r = Rectangle(top_left, bottom_right)
            r.draw(win)
            top_left.move(20, 0)
            bottom_right.move(20, 0)

        top_left.move(-100, 20)
        bottom_right.move(-100, 20)

win = GraphWin("pattern", 100, 100)

patch2()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM