我正在尝试以用户指定的大小初始化蓝色矩形网格。但是,矩形不会在初始化的画布上绘制。我试图将它们存储在矩阵中以供以后操作。我的代码如下:
import Tkinter
import sys
from math import floor
master = Tkinter.Tk()
xboxes = int(sys.argv[1])
yboxes = int(sys.argv[2])
winx = 800
winy = 600
w = Tkinter.Canvas(master, width=winx, height=winy)
squares = [[None]*5 for i in range(5)]
w.pack()
for i in range(yboxes):
for j in range(xboxes):
initx = floor(winx / xboxes * j)
inity = floor(winy / yboxes * i)
sizex = floor(winx / xboxes * j)
sizey = floor(winy / yboxes * i)
squares[i][j] = w.create_rectangle(initx, inity, sizex, sizey, fill="red")
master.mainloop()
知道它为什么不起作用?任何帮助将不胜感激。
答案 0 :(得分:1)
我用# <--
评论了更改的部分。
create_rectangle
接受x1, y1, x2, y2
(不是x, y, xsize, ysize
)。
try:
import Tkinter
except ImportError:
import tkinter as Tkinter
import sys
from math import floor
master = Tkinter.Tk()
xboxes = int(sys.argv[1])
yboxes = int(sys.argv[2])
winx = 800
winy = 600
w = Tkinter.Canvas(master, width=winx, height=winy)
squares = [[None]*xboxes for i in range(yboxes)] # <-- changed hard-coded 5; to use passed argument
w.pack()
for i in range(yboxes):
for j in range(xboxes):
initx = floor(winx / xboxes * j) # <--
inity = floor(winy / yboxes * i) # <--
endx = floor(winx / xboxes * (j+1)) # <-- with `j`, It draw dot instead of rectangle.
endy = floor(winy / yboxes * (i+1)) # <--
squares[i][j] = w.create_rectangle(initx, inity, endx, endy, fill="red")
master.mainloop()