Search code examples
pythonpython-3.xtkintercenteringdrawrectangle

How can I center a tkinter rectangle?


I have everything I'd like my code to perform, but it is bugging me that the square is not centered. I've been searching the internet for hours...please help! I have tried using anchor = "center" and .place() but I just can't seem to get it right.

from tkinter import *
import random

class draw():
     def __init__(self, can, start_x, start_y, size):
     self.can = can
     self.id = self.can.create_rectangle((start_x, start_y,start_x+size, start_y+size), fill="red")
     self.can.tag_bind(self.id, "<ButtonPress-1>", self.set_color)
     self.color_change = True

def set_color(self,event = None):
    self.color_change = not self.color_change
    colors = ["red", "orange", "yellow", "green", "blue", "violet","pink","teal"]
    self.can.itemconfigure(self.id, fill = random.choice(colors))


root = Tk()
canvas = Canvas(root)
canvas.grid(column=1, row=1)
square = draw(canvas,1,1,90)


root.mainloop()

Solution

  • By defining a height and a width for the canvas and using pack() instead of grid() (like so)

    from tkinter import *
    import random
    
    class draw():
         def __init__(self, can, start_x, start_y, size):
           self.can = can
           self.id = self.can.create_rectangle((start_x, start_y,start_x+size, start_y+size), fill="red")
           self.can.tag_bind(self.id, "<ButtonPress-1>", self.set_color)
           self.color_change = True
    
         def set_color(self,event = None):
            self.color_change = not self.color_change
            colors = ["red", "orange", "yellow", "green", "blue", "violet","pink","teal"]
            self.can.itemconfigure(self.id, fill = random.choice(colors))
    
    
    WIDTH = 400 #change as needed
    HEIGHT = 500 #change as needed
    root = Tk()
    canvas = Canvas(root, height=HEIGHT, width=WIDTH)
    canvas.pack()
    square = draw(canvas,WIDTH/2,HEIGHT/2,10)
    
    
    root.mainloop()
    

    You can center the rectangle