draw rectangle tkinter not functioning
As @BryanOakley comments, the provided source contains uncompleted analysis and reveals misunderstandings of tkinter use.
Problem 1 - the class Rectangle
doesn't need to inherit from tk.Tk
.
Instead of inheriting the
class Rectangle
fromtk.Tk
, add theCanvas
instance at instance creation.
class Rectangle(): # not inherit from ==> tk.Tk): def __init__(self,canvas): # not initialize a second Tk instance ==> tk.Tk.__init__(self) self.x = self.y = 0 # attach the main canvas self.canvas = canvas self.canvas.pack(side="top", fill = "both", expand = True)
Instead of:
class Rectangle(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.x = self.y = 0 self.canvas.pack(side="top", fill = "both", expand = True)
Problem 2 - no instance of the class Rectangle
has been created.
To use the
class Rectangle
, an instance shall be created and attached to thecanvas
instance !!Before, move the class declaration before
Tk()
andCanvas()
creation.
class Rectangle(tk.Tk): def __init__(self):... def release(self, event): pass# Other Classes for arc and pencil begin hereroot = Tk()canvas = Canvas(root, width = w, height = h, bg='#D2B48C', cursor = "cross")canvas.pack()# create the Rectangle instancehRect = Rectangle(canvas)root.mainloop()
Instead of:
root = Tk()canvas = Canvas(root, width = w, height = h, bg='#D2B48C', cursor = "cross")canvas.pack()class Rectangle(tk.Tk): def __init__(self):... def release(self, event): pass# Other Classes for arc and pencil begin hereroot.mainloop()
For one, you never create an instance of the Rectangle
class which is where all your logic is.
For another, you must only have a single instance of Tk
. You create one at the start of the problem, and then you'll create another if you create an instance of Rectangle
. Again, you can only have one.