How do I create a class called rectangle that I can pass it the coordinates and a color and have it fill those one?
from Tkinter import *
master = Tk()
w = Canvas(master, width=300, height=300)
w.pack()
class rectangle():
def make(self, ulx, uly, lrx, lry, color):
self.create_rectangle(ulx, uly, lrx, lry, fill=color)
rect1 = rectangle()
rect1.make(0,0,100,100,'blue')
mainloop()
Here is one way of doing it. First, to draw the rectangle on the Tk Canvas you need to call the
create_rectanglemethod of the Canvas. I also use the__init__method to store the attributes of the rectangle so that you only need to pass the Canvas object as a parameter to the rectangle’sdraw()method.EDIT
Answering your question: what is the
*in front ofself.coords?To create a rectangle on a Tk Canvas you call the
create_rectanglemethod as follows.So each of the coords (
x0,y0, etc) are indiviual paramaters to the method. However, I have stored the coords of the Rectangle class in a single 4-tuple. I can pass this single tuple into the method call and putting a*in front of it will unpack it into four separate coordinate values.If I have
self.coords = (0, 0, 1, 1), thencreate_rectangle(*self.coords)will end up ascreate_rectangle(0, 0, 1, 1), notcreate_rectangle((0, 0, 1, 1)). Note the inner set of parentheses in the second version.The Python documentation discusses this in unpacking argument lists.