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.
frame = Frame(master,**options) frame.pack()
Now, let’s look at some options that we can use with tkinter frame.
|background||Set the background color of the frame.|
|borderwidth||Set the border width of the frame.|
|colormap||Set the colormap to use for the frame and its child widgets.|
|cursor||Set the mouse cursor to show when hovering over the frame.|
|height||Set the height of the frame. default is 0.|
|padx||Set the horizontal padding of the frame.|
|pady||Set the vertical padding of the frame.|
|relief||Set the border style for the frame. use FLAT(default), SUNKEN, RAISED, GROOVE and RIDGE|
|width||Set 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.
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.
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()
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()
That’s a wrap for this tutorial. if you have any questions then please feel free to comment below.