Cadel Watson
Cadel Watson

Reputation: 43

Tkinter won't draw rectangles on Canvas

I'm trying to initialise a grid of blue rectangles at a size specified by the user. However, the rectangles are not drawing on the initialised canvas. I'm trying to store them in a matrix for later manipulation. My code is as follows:

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()

Any idea why it isn't working? Any help would be much appreciated.

Upvotes: 0

Views: 972

Answers (1)

falsetru
falsetru

Reputation: 368914

I commented changed parts with # <--.

create_rectangle accepts x1, y1, x2, y2 (not 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()

Upvotes: 1

Related Questions