Python Tkinter: Placing buttons in frame

Viewed 16785

I'm trying to create different frames and switch/destroy them so that you can move between windows like you would in a normal iOS app.

To do so, I need to place the widgets (components) in frames (containers).

However, when I try to add a button to the frame it doesn't pack it to the right side.

Here is my code: from tkinter import *

root=Tk()
root.geometry('500x500')
root.title('Good morning :)')

frame1=Frame(root,width=500,height=500,bg='green')
frame1.pack()

button1=Button(frame1,text='Hello')
button1.pack(side='bottom')
1 Answers

You need to expand the Frame to fill the entire top-level window, and you need to tell the Button to pack on side='right' instead of side='bottom'.
And you need to run root.mainloop() at the end.

from tkinter import *

root = Tk()
root.geometry('500x500')
root.title('Good morning :)')

frame1 = Frame(root, bg='green')
frame1.pack(expand=True, fill=BOTH)

button1 = Button(frame1, text='Hello')
button1.pack(side=RIGHT)

root.mainloop()

Also, you don't need the dimensions in the Frame statement, since it will expand to the full 500x500 stated in the geometry with the extra keyword arguments passed to the pack() function. By default, the Frame is only going to be big enough to hold the widgets inside it, so it will only be as big as the Button, unless you tell it to expand to the full size of the top-level root widget.

Related