Skip to content Skip to sidebar Skip to footer

How To Center A Tkinter Widget?

I have Tkinter window with canvas and label with 200x200 picture on it. I want label to be in the center of the window, regardless of the window size. from Tkinter import * import

Solution 1:

Use the place geometry manager. Here is a simple example :

from tkinter import *

wd = Tk()
wd.config(height=500, width=500)
can = Canvas(wd, bg = 'red', height=100, width=100)
can.place(relx=0.5, rely=0.5, anchor=CENTER)

Basically the options work as follows:

With anchor you specify which point of the widget you are referring to and with the two others you specify the location of that point. Just for example and to get a better understanding of it, let's say you'd be sure that the window is always 500*500 and the widget 100*100, then you could also write (it's stupid to write it that way but just for the sake of explanation) :

from tkinter import *

wd = Tk()
wd.config(height=500, width=500)
can = Canvas(wd, bg = 'red', height=100, width=100)
can.place(x=200, y=200, anchor=NW)

relx and rely give a position relative to the window (from 0 to 1) : 0,4*500 = 200 x and y give absolute positions : 200 anchor=NW makes the offset options refer to the upper left corner of the widget

You can find out more over here :

http://effbot.org/tkinterbook/place.htm

And over here :

http://www.tutorialspoint.com/python/tk_place.htm

Post a Comment for "How To Center A Tkinter Widget?"