yil98
yil98

Reputation: 33

Tkinter - How to center a Widget (Python)

I started with the GUI in Python and have a problem. I've added widgets to my frame, but they're always on the left side. I have tried some examples from the internet, but I did not manage it . I tried .place, but it does not work for me. Can one show me how to place the widgets in the middle?

Code:

import tkinter as tk

def site_open(frame):
    frame.tkraise()

window = tk.Tk()

window.title('Test')
window.geometry('500x300')

StartPage = tk.Frame(window)
FirstPage = tk.Frame(window)

for frame in (StartPage, FirstPage):
    frame.grid(row=0, column=0, sticky='news')

lab = tk.Label(StartPage, text='Welcome to the Assistant').pack()
lab1 = tk.Label(StartPage, text='\n We show you helpful information about you').pack()
lab2 = tk.Label(StartPage, text='\n \n Name:').pack()
ent = tk.Entry(StartPage).pack()
but = tk.Button(StartPage, text='Press', command=lambda:site_open(FirstPage)).pack()

lab1 = tk.Label(FirstPage, text='1Page').pack()
but1 = tk.Button(FirstPage, text='Press', command=lambda:site_open(StartPage)).pack()

site_open(StartPage)
window.mainloop()

Upvotes: 0

Views: 3450

Answers (2)

cercle
cercle

Reputation: 1

You are mixing two different Layout Managers. I suggest you either use The Grid Geometry Manager or The Pack Geometry Manager.

Once you have decided which one you would like to use, it is easier to help you :)

For example you could use the Grid Geometry Manager with two rows and two columns and place the widgets like so:

label1 = Label(start_page, text='Welcome to the Assistant')
# we place the label in the page as the fist element on the very left 
# and allow it to span over two columns
label1.grid(row=0, column=0, sticky='w', columnspan=2) 

button1 = Button(start_page, text='Button1', command=self.button_clicked)
button1.grid(row=1, column=0)

button2 = Button(start_page, text='Button2', command=self.button_clicked)
button2.grid(row=1, column=1)

This will lead to having the label in the first row and below the two buttons next to each other.

Upvotes: 0

figbeam
figbeam

Reputation: 7176

After you have created window, add:

window.columnconfigure(0, weight=1)

More at The Grid Geometry Manager

Upvotes: 2

Related Questions