Tkinter Frame

In this short guide, I will teach you about the Tkinter frame widget in python. I will also be discussing various options that we can use along with the code examples. so let’s get started.

The frame is the standard widget provided by Tkinter that helps to organize a group of complex widgets. Its rectangular shape acts as a container where it can hold widgets.

We can also use it to add some padding or as a base class while implementing a custom widget.

Here is the syntax of frame widget.

Syntax :

frame = Frame(master,**options)
frame.pack()

Now, let’s look at some options that we can use with tkinter frame.

backgroundSet the background color of the frame.
borderwidthSet the border width of the frame.
colormapSet the colormap to use for the frame and its child widgets.
cursorSet the mouse cursor to show when hovering over the frame.
heightSet the height of the frame. default is 0.
padxSet the horizontal padding of the frame.
padySet the vertical padding of the frame.
reliefSet the border style for the frame. use FLAT(default), SUNKEN, RAISED, GROOVE and RIDGE
widthSet the width of the frame.default is 0.

Tkinter Frame Examples

For a better understanding of the concepts let’s look at some code examples.

In the below examples, I have used the button widget for demonstration purposes. Read more about the Tkinter button.

Example 1

In this code example, we will create a simple frame and place a button inside it.

from tkinter import *

window = Tk()

frame1 = Frame(window)
frame1.pack()

b = Button(frame1,text = "Inside Frame")
b.pack()

window.mainloop()

Save and run the above code, you should see the following output.

Output :

tkinter frame code example 1 output

Example 2

In the below code, we will create two frames and place one button inside each of them.

from tkinter import *

window = Tk()

frame1 = Frame(window,bg = "black")
frame1.pack(side = TOP,ipadx=30,ipady = 10)

Button(frame1,text = "Inside Frame 1").pack()


frame2 = Frame(window,bg = "grey")
frame2.pack(side = TOP,ipadx=30,ipady = 10)

Button(frame2,text = "Inside Frame 2").pack()

window.mainloop()

Output :

tkinter frame code example 2 output

Example 3

The purpose of this final code example is to show that we can use a different geometry inside the frame.

For example, We have the pack geometry manager in the master window but we have used the grid manager inside the frame.

from tkinter import *

window = Tk()

frame1 = Frame(window,bg = "black")
frame1.pack()

Button(frame1,text = "btn 1").grid(row = 0,column = 0)
Button(frame1,text = "btn 2").grid(row = 0,column = 1)

window.mainloop()

Output :

tkinter frame code example 3 output

That’s a wrap for this tutorial. if you have any questions then please feel free to comment below.

Leave a Reply