Tkinter: Center label in frame of fixed size?

I am trying to create a frame of fixed size and place a text label in the center. I am not sure why this isn't working. I want the frame in the top left of the master frame, so NW is specified and that works fine. But changing the sticky direction of the label doesn't do anything. Help is appreciated.

self.f = Frame(self.master,bg="yellow",width=50,height=50)
self.f.grid(row=0,column=0,sticky="NW")
self.f.grid_propagate(0)
self.f.update()
self.l = Label(self.f,text="123",anchor="center",bg="yellow")
self.l.grid(column=0,row=0,sticky="wens")
2

1 Answer

You can use .place() for your label since your frame and your label have different parents. In place() you can use anchor="center" specify the startingpoint of your "anchor" with: x and y. Here is a working example:

app = Tk()
f = Frame(app,bg="yellow",width=50,height=50)
f.grid(row=0,column=0,sticky="NW")
f.grid_propagate(0)
f.update()
l = Label(f,text="123",bg="yellow")
l.place(x=25, y=25, anchor="center")
app.mainloop()
6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like