Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to place objects in the middle of a frame using tkinter?

I want to create a game that can be played in full screen and in any other window size. For this I have code creating a frame, two buttons and a label. I want the Buttons and the label to be in the center of the frame, but I can't figure out how to do that.

As a temporary solution, I placed a empty black label on top of the buttons, but now this won't work with my ideas.

Here is the code I have now:

import tkinter as tk

def startgame():
    pass

mw = tk.Tk()
mw.title('The Game')

back=tk.Frame(master=mw, width=500, height=500, bg='black')
back.pack_propagate(0) 
back.pack(fill=tk.BOTH, expand=1) #Adapts the size to the window

#Here I had the label

go = tk.Button(master=back, text='Start Game', command=startgame, bg='#111', fg='red')
go.pack()
close = tk.Button(master=back, text='Quit', command=mw.destroy, bg='#111', fg='red')
close.pack()
info = tk.Label(master=back, text='Made by me!', bg='red', fg='black')
info.pack()

mw.mainloop()

Question: How to set the buttons etc to the middle constantly?

like image 568
Erich Schmidt Avatar asked Apr 13 '16 09:04

Erich Schmidt


1 Answers

There are many ways to center a widget in another wiget. In the following examples it is assumed you want back to remain its original size, and for it to be centered in the root window. Once you have this widget centered, you can then focus on placing the inner widgets inside it however you choose, and the frame will remain centered.

Note: to have back shrink to fit the buttons (while still remaining centered), remove this line:

back.pack_propagate(0) 

Using pack

With pack, you want to turn expansion on (expand=True) but not have the widget fill its area (fill="none").

back.pack(fill="none", expand=True)

Using grid

Using grid, the technique is to create a 3x3 grid, with the frame in the center cell. You must then make sure that all rows and columns except the center one are given a weight, so that any extra space goes to them rather than go in the center:

back.grid(row=1, column=1)
mw.grid_rowconfigure(0, weight=1)
mw.grid_rowconfigure(2, weight=1)
mw.grid_columnconfigure(0, weight=1)
mw.grid_columnconfigure(2, weight=1)

Using place

Arguably the simplest solution is to use place. With place you simply instruct tkinter to place the center of the widget at a relative x and y position of .5

back.place(relx=.5, rely=.5, anchor="center")
like image 106
Bryan Oakley Avatar answered Oct 13 '22 21:10

Bryan Oakley