Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a widget vertically in Tkinter?

Tags:

tkinter

This code only centers horizontally, how can I make the progress bar also centered vertically ?

import Tkinter
import ttk
root = Tkinter.Tk()
root.geometry("=500x500")
root.progressbar = ttk.Progressbar(root)
root.progressbar.pack(anchor=Tkinter.CENTER)
root.mainloop()

Screenshot

like image 826
ychaouche Avatar asked Oct 23 '25 04:10

ychaouche


2 Answers

In this specific case, adding expand=True to the pack statement will suffice.

Don't take this as general purpose advice for how to center any widget in any situation. expand=True isn't a secret alias for "center this". It just so happens that in this specific case, the combination of expand with the lack of the use of the fill attribute, the fact that the window is bigger than the progress bar, and the fact there aren't any other widgets, all works together to center this specific widget.

Another way you can center a widget -- especially if it's the only widget in an area -- is to use place. This is one of the few times where place might be better than grid or pack. place allows you to explicitly place a widget in the center of its container.

For example:

root.progressbar.place(relx=.5, rely=.5, anchor="c")

This says "place the center of the widget at 50% the width of the container and 50% of the height of the container".

like image 91
Bryan Oakley Avatar answered Oct 27 '25 05:10

Bryan Oakley


If you have multiple widgets you want to center and don't want them overlapping, you can put them all into a frame and center the frame with the place() method as Bryan Oakley showed.

like image 24
CopperyMarrow15 Avatar answered Oct 27 '25 05:10

CopperyMarrow15



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!