Skip to content Skip to sidebar Skip to footer

Help Creating Python Class With Tkinter

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=30

Solution 1:

Here is one way of doing it. First, to draw the rectangle on the Tk Canvas you need to call the create_rectangle method 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's draw() method.

from Tkinter import *

class Rectangle():
    def __init__(self, coords, color):
        self.coords = coords
        self.color = color

    def draw(self, canvas):
        """Draw the rectangle on a Tk Canvas."""
        canvas.create_rectangle(*self.coords, fill=self.color)

master = Tk()
w = Canvas(master, width=300, height=300)
w.pack()

rect1 = Rectangle((0, 0, 100, 100), 'blue')
rect1.draw(w)

mainloop()

EDIT

Answering your question: what is the * in front of self.coords?

To create a rectangle on a Tk Canvas you call the create_rectangle method as follows.

Canvas.create_rectangle(x0, y0, x1, y1, option, ...)

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), then create_rectangle(*self.coords) will end up as create_rectangle(0, 0, 1, 1), not create_rectangle((0, 0, 1, 1)). Note the inner set of parentheses in the second version.

The Python documentation discusses this in unpacking argument lists.


Post a Comment for "Help Creating Python Class With Tkinter"