'Tkinter: How to make a button center itself?
I'm making a program in Python and I want to go with a layout that is a bunch of buttons in the center. How do I make a button center itself using pack()?
Solution 1:[1]
To center horizontally this should be enough
button.pack(side=TOP)
But to center horizontally and vertically you could use nested frames. Check the following script:
import tkinter as tk
#%% Frames
frameA = tk.Frame(background="#c8c8c8")
frameB = tk.Frame(width=200, height = 200, background="#646464")
# Nested Frame. framebb is created within frameB without width or height
framebb = tk.Frame(frameB, background="#646464")
frameC = tk.Frame(width=100, height = 100, background="bisque")
frameA.pack(side='top', fill=None)
frameB.pack(side='top')
# expand is the key parameter to center the framebb within frameB
framebb.pack(expand=True)
frameC.pack(side='bottom')
#frameA.pack_propagate(False)
frameB.pack_propagate(False)
frameC.pack_propagate(False)
#%% Buttons and Labels
tk.Label(frameA, text = "Text within the frame A").pack()
a = tk.Button(framebb, text = "A").pack()
b = tk.Button(framebb, text = "B").pack()
c = tk.Button(framebb, text = "C").pack()
d = tk.Button(frameC, text = "D").pack()
e = tk.Button(frameC, text = "E").pack()
tk.mainloop()
Another approach could be using the .grid()
method
button.grid(row=1,col=0)
the values of row=1,col=0
depend of the position of the other widget in your window
or you can use .place(relx=0.5, rely=0.5, anchor=CENTER)
button.place(relx=0.5, rely=0.5, anchor=CENTER)
Notice that the parameter anchor
is referencing the a relative position to the object (in this case button). anchor
is not referencing to a position in the window. You could think that the button is a ship that has several anchors so you should choose a coordinate and which anchor you want to fix in that coordinate.
Example using .place()
:
from tkinter import * # Use this if use python 3.xx
#from Tkinter import * # Use this if use python 2.xx
a = Button(text="Center Button")
b = Button(text="Top Left Button")
c = Button(text="Bottom Right Button")
# You can use the strings the referencing the relative position on the button
# strings = n, ne, e, se, s, sw, w, nw, c or center
# Or you can use the constants of tkinter
# N, NE, E, SE, S, SW, W, NW, CENTER
a.place(relx=0.5, rely=0.5, anchor=CENTER)
b.place(relx=0.0, rely=0.0, anchor=NW)
c.place(relx=1.0, rely=1.0, anchor=SE)
mainloop()
Solution 2:[2]
this is slightly old now, you have to do this:
import tkinter as tk #you can do 'from tkinter import *', any is fine
btn = tk.Button(text = "Centered Button")
btn.place(relx=0.5, rely=0.5, anchor='center')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | YMJA |