How can I center a tkinter rectangle? How can I center a tkinter rectangle? tkinter tkinter

How can I center a tkinter rectangle?


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

from tkinter import *import randomclass 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 neededHEIGHT = 500 #change as neededroot = 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


Your starting position is being set by your call to the draw method. You can have it automatically detect the correct center by calculating it from the canvas object.

size = 90center_height = canvas.winfo_reqheight() / 2 - size / 2center_width = canvas.winfo_reqwidth() / 2 - size / 2square = draw(canvas, center_width, center_height, size)

You could also set start_x and start_y in the draw method if you'd prefer.