用于python图形的循环



我正在为我的一个学校项目优化我的代码。我正在尝试使用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 

相关内容

  • 没有找到相关文章

最新更新