For循环python个图形

For loop of python graphics

我正在为我的学校项目优化我的代码。我正在尝试使用 Python 图形库绘制网格。当我 运行 循环时,它会继续添加行,但 x1 和 x2 值不会像我需要的那样返回到它们的原始值。它在该行最后一个正方形的 (x2, y2) 点处扩展下一行。任何有关如何解决此问题的见解都将不胜感激!

import random, graphics
from graphics import *

x1 = 5
x2 = 65
y1 = 5
y2 = 65

def make_square(x1, x2, y1, y2):

    location = graphics.Rectangle(graphics.Point(x1, y1), graphics.Point(x2, y2))
    location.draw(win)
    
win = graphics.GraphWin("Minesweeper", 545, 570)
win.setBackground(color_rgb(250, 249, 246))

for i in range(9):
    for j in range(9):
        make_square(x1, x2, y1, y2)
        x1 = x1 + 60
        x2 = x2 + 60
    y1 = y1 + 60
    y2 = y2 + 60
     
win.getMouse() # Pause to view result, click on window to close it
win.close() # Close window when done 

因此,在开始绘制新行时,您想要重置 x1x2,这是有道理的,因为下一行将与前一行从相同的 x 位置开始排。您是否尝试将 x1 = 5x2 = 65 添加到外部 for 循环的开头,而不是在循环外定义它们?

这样看:你在外循环外定义 y,因为它遍历行,你在内循环外定义 x,因为它遍历列:

import random, graphics
from graphics import *


def make_square(x1, x2, y1, y2):

    location = graphics.Rectangle(graphics.Point(x1, y1), graphics.Point(x2, y2))
    location.draw(win)
    

win = graphics.GraphWin("Minesweeper", 545, 570)
win.setBackground(color_rgb(250, 249, 246))

y1 = 5
y2 = 65
for i in range(9):
    x1 = 5
    x2 = 65
    for j in range(9):
        make_square(x1, x2, y1, y2)
        x1 = x1 + 60
        x2 = x2 + 60
    y1 = y1 + 60
    y2 = y2 + 60
     
win.getMouse() # Pause to view result, click on window to close it
win.close() # Close window when done