Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Tkinter: Placing buttons in frame

Tags:

button

tkinter

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')
like image 881
E.K Avatar asked Nov 21 '17 21:11

E.K


People also ask

How do I position buttons in Tkinter?

The button in the tkinter module can be placed or move to any position in two ways: By using the place() method. And by using the pack() method.

How do you add a button to a frame in Python?

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.

How do you align buttons in Python?

Pack() has three options you can use: side, fill, expand. The side option aligns buttons horizontally. The fill option aligns buttons vertically. The expand option takes up the full height of the frame.

Can I use grid in a frame Tkinter?

This method can be used on both windows and frames. The grid() method allows you to indicate the row and column positioning in its parameter list. Both row and column start from index 0. For example grid(row=1, column=2) specifies a position on the third column and second row of your frame or window.


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.

like image 143
Gary02127 Avatar answered Oct 10 '22 13:10

Gary02127