Layout Management using Python Tkinter

by Apr 7, 2020Python Tkinter Examples

In this tutorial, you will be learning “How to layout your GUI using Python”. The following are the topics that will be covered in this article.

  1. Python Tkinter Label Frames
  2. Tkinter Geometry Matrix
  3. Creating menu bars
  4. Creating tabbed widgets

1. Python Tkinter Label Frames:

Label Frame is a frame typed container where you can put other widgets into which also has a label attached to it so you can name the collection of widgets. The following are the list of functions in Label Frame

heightwidthlabelanchorcursorrelief
fgbgbdpadxpady

LabelFrames also have similar syntax like Labels. Below is the example of Adding Label Frame.

If you’re new to Python Tkinter. I recommend you to go through this first.

from tkinter import *
new=Tk()
new.geometry('640x300')
new.title('IoT4Beginners')

labelframe = LabelFrame(new, text='LabelFrame Title here') #adding a labelframe to the window
labelframe.pack() 	           #organizing the widget into frame
l=Label(labelframe,text='Hello guys, This is inside Label Frame') 		
      
l.pack()
mainloop()

– Output of Basic Label Frame Program

List of functions of Label Frame and examples:

height

It defines the vertical dimension of the new frame.

width

It defines the horizontal dimension of the new frame.

labelanchor

Represents where to display the label text or (name) in compass directions. This has different positions like “N” indicates north, “S” indicates South, “W” indicates West, “E” indicates East.

labelframe = LabelFrame(new,labelanchor=N,text='North',padx=10,pady=10)	 

cursor

To change the type of cursor(mouse pointer) when it is over the widget. There are many cursors available. Here are some of the following

labelframe=LabelFrame(new,cursor='circle',text='FrameName',padx=10,pady=10)
ArrowfleurPlus
CircleHand1Sailboat
ClockHand2Target
CrossHeartTrek
DotboxManWatch
exchangepiratexterm

relief

It is used to set the border type of the frame.  The following types are FLAT, RAISED, SUNKEN, and RIDGE. 

labelframe=LabelFrame(new,text='FrameName',padx=20,pady=10,relief=SUNKEN)

fg

It is used to set the colour for the text of the label frame.

labelframe = LabelFrame(new,text='FrameName',bg='aqua',padx=20,pady=20)

bg

It is used to set the background colour for the widget.

labelframe = LabelFrame(new,text='FrameName',bg='aqua',padx=20,pady=20)

bd

It is used to set the border width of the label frame.

labelframe = LabelFrame(new, text='LabelFrame Title here', bd=12)

padx and pady

padx – Space added to the left and right of the text in the frame

pady – Space added to the top and bottom of the text in the frame

labelframe = LabelFrame(new,text='FrameName',padx=20,pady=20)

Ok, What if we want to have multiple widgets in the same label frame? Let’s see if it is possible.

from tkinter import *

new = Tk()
new.geometry('640x300')
new.title('IoT4Begineers')

labelframe = LabelFrame(new, text='LabelFrame Title here')
labelframe.pack()
l = Label(labelframe, text='Label Text')
l.pack()
b= Button(labelframe, text='Button')
b.pack()
mainloop()

Ok, it is possible to add different and multiple widgets in the same label fame. What if we want them to arrange in a different position? Here comes the

2. Tkinter Geometry Managers

Tkinter Geometry Managers are used to arrange widgets in Tkinter. There are three geometry managers. They are

grid()

grid() geometry is used to arrange widgets in a table-like structure.

Let us make a window named IOT4Engineers which has no widgets inside it, will look like below

Now, Let’s imagine the above window consists of a table-like structure having rows and column which will be easy to arrange widgets in a perfect position.

Syntax:

            Widget_name.grid(options)

There are different options which have different uses.

  1. Row – In what row, Widget should be aligned to.
  2. Column – In what column, the widget should be aligned to.
  3. Columnspan – How much column widget should span
  4. Rowspan – How much row widget should span
  5. Padx – Space added between left and right of widget’s border(outside)
  6. Pady –  Space added between top and bottom of widget’s border(outside)
  7. Ipadx – Space added between left and right of widget’s border(inside)
  8. Ipady – Space added between top and bottom of widget’s border(inside)
  9. Sticky – similar to label anchor where the position is named in compass direction NSEW

Let’s see an example combining all the options.

from tkinter import *
window = Tk()
window.title('IOT4Engineers')
window.geometry('640x400')
new = LabelFrame(window,text='Grid Options')
new.pack(fill='both', expand='yes')

sticky = Label(new, bg="lime", text='North East')
sticky.grid(row=8, column=0,sticky=SW)

rows = Label(new,height='3',width='25',bg="red", text='Row=0 Column=0') 
rows.grid(row=0,column=0)

column = Label(new,height='3',width='25', bg="yellow",text='Row=0 Column=1')
column.grid(row=0,column=1)

columnpan1 = Label(new,bg='mediumpurple', text='Column Span=1, The text only takes one column')
columnpan1.grid(row=1,column=0,columnspan=1)

columnpan = Label(new,bg='coral', text='Column Span=2, The text extend till 2nd Column')
columnpan.grid(row=2,column=0,columnspan=2)


rowspan = Label(new, bg="yellow",text='Rowspan=1, This takes only one Row')
rowspan.grid(row=3,column=1,rowspan=1)

padx = Label(new, bg="skyblue",text='Padx=1, Row=4 Column=1')
padx.grid(row=4,column =1,padx=50)

pady = Label(new, bg="skyblue",text='Pady=40,Row=5, Column=1')
pady.grid(row=5,column=1,padx=0,pady=40)

ipadx = Label(new, bg="yellow", text='ipadx=10')
ipadx.grid(row=6, column=0,ipadx=10)

ipadx1 = Label(new, bg="yellow", text='ipadx=30')
ipadx1.grid(row=6, column=1,ipadx=30)

ipady = Label(new, bg="lightgreen", text='ipady=10')
ipady.grid(row=7, column=0,ipady=10)

ipady1 = Label(new, bg="lightgreen", text='ipady=30')
ipady1.grid(row=7, column=1,ipady=30)

new.mainloop()

pack()

This geometry manager organizes widgets in blocks before placing them in the parent widget.

So, What is the difference between the grid and the pack manager?

Pack function has limited options when comparing with Grid manager, but at most simple programs pack manager is used because of its simple options.

Syntax:

            Widget_name.pack(options)

The options of Pack()  are

  1. fill
  2. expand
  3. side

fill

To specify how much space should widget should occupy. You can use X if you want to occupy horizontally, Y if you want to occupy vertically or BOTH to occupy both spaces.

expand

The widget expands to fill any space not used. YES indicates to expand, NO indicates not to expand

side

To determine which side the widget should display. TOP for top-side, BOTTOM for bottom-side, LEFT for left-side and RIGHT for right-side.

Example combining all the options,

from Tkinter import *

new = Tk()
new.geometry('640x300')
new.title('IoT4Begineers')

labelframe = LabelFrame(new, text='LabelFrame Title here')
labelframe.pack(fill=BOTH, expand= YES)
l = Button(labelframe, text='X - Expand: YES')
l.pack(fill=X, expand =YES)
b= Button(labelframe, text='Y - Expand: YES')
b.pack(fill=Y, expand =YES)
c= Button(labelframe,text='Side:Left')
c.pack(side=LEFT)
mainloop()

place()

place() geometry manager is used to place the widget in a specific position. It is the simplest manager among the three.

Syntax:

Widget_name.place(options)

List of Options of Place geometry manager

  1. Height – Height of the widget in pixels
  2. Width –  Width of the widget in pixels
  3. Relheight – Similar to Height but the range is from 0.0 – 1.0
  4. Relwidth – Similar to Width but the range is from 0.0 – 1.0
  5. X – Horizontal offset of the window  
  6. Y – Vertical offset of the window       
  7. Relx – Similar to X but the range is from 0.0 – 1.0
  8. Rely – Similar to Y but the range is from 0.0 – 1.0
  9. Anchor – Alignment indication of widgets using compass directions.
  10. Bordermode – Inside(Inside the border), Outside(Outside the border)

Let’s see an example including all the options,

from tkinter import *

labelframe = Tk()
labelframe.geometry('640x300')
labelframe.title('IoT4Begineers')

l=Button(labelframe, text='H=100 W=100')
l.place(height=100, width=100)

b=Button(labelframe, text='X=100 RH=0.2 RW=0.2')
b.place(x=100,relheight=0.2, relwidth=0.2)

c=Button(labelframe,text='X=500, Y=250')
c.place(x=500,y=250)

d=Button(labelframe,text='relx=0.4, rely=0.3')
d.place(relx=0.4,rely=0.3)

f=Button(labelframe,text='Bordermode = INSIDE')
f.place(x= 350,bordermode = INSIDE)

mainloop()

3. Creating menu bars:

In this topic, we will learn how to add menu bars to our main window, add menus to the menu bar and add menu items to the menus.

Syntax:

            menubar_name=Menu(options)

The options of the menubar are similar to the Labelframe. Some of the different options are

  • Selectcolor – Colour for the check buttons and radio buttons
  • Tearoff – Position of the menu bar, Starts from position 0
  • Image – To display an image on this menubutton
  • Activebackground – Background colour of the menu when it is clicked.
  • Activeforeground – Foreground colour of the menu

The main methods used in menus are

  1. Add_command –  To add a menu
  2. Add_seperator –  To add a separator line to the menu
  3. Add_radiobutton –  To add a radiobutton in the menu
  4. Add_checkbutton – To add checkbutton in the menu
  5. Add_cascade  – Associating a given menu to parent menu
  6. Add(type) – To add a specific type of menu

Here the basic example of creating menu’s

from tkinter import *

labelframe = Tk()
labelframe.geometry('640x300')
labelframe.title('IoT4Begineers')

menu_bar=Menu(labelframe)
menu_bar.add_command(label='Hello')
menu_bar.add_command(label='IOT4Begineers')

labelframe.config(menu=menu_bar)

mainloop()

Now, I will show you how to add menus to this menu bar,

from tkinter import *

labelframe = Tk()
labelframe.geometry('640x300')
labelframe.title('IoT4Begineers')

menu_bar=Menu(labelframe)
file = Menu(menu_bar,tearoff=0)
file.add_command(label='Welcome')
menu_bar.add_cascade(label='IOT4Begineers',menu = file)
labelframe.config(menu=menu_bar)

mainloop()

Ok, now let’s add a function to the menu, For example, we will make the menu to display “Nice to meet you” in Output box and make one more menu named quit and add the function of closing the window to the “Quit” menu.

from tkinter import *

labelframe = Tk()
labelframe.geometry('640x300')
labelframe.title('IoT4Begineers')

def Welcome():
    print('Nice to meet you!')

menu_bar=Menu(labelframe)
file = Menu(menu_bar,tearoff=0)
file.add_command(label='Welcome',command=Welcome)
file.add_separator()

file.add_command(label="Quit",command=labelframe.quit)
menu_bar.add_cascade(label='IOT4Begineers',menu = file)
labelframe.config(menu=menu_bar)

mainloop()



– Output of displaying “Nice to meet you!” in console
-Output of Window getting closed when Quit is clicked

4. Creating tabbed widgets:

The tabbed widgets are called Notebooks in Tkinter, It manages a collection of windows and displays on a single window.

Syntax:

Tab_name=ttk.Notebook(options)

The options used in tabbed widgets are

  • Height – Height of the widget.
  • Width – Width of the widget.
  • Padding – Space around the outside of tab.

Ok, let’s Create a simple tabbed widget contained window.

from tkinter import *
from tkinter import ttk

labelframe = Tk()
labelframe.geometry('640x300')
labelframe.title('IoT4Begineers')

tabs = ttk.Notebook(labelframe)
first = ttk.Frame(tabs)
tabs.add(first, text='First')
second = ttk.Frame(tabs)
tabs.add(second, text='Second')
a = Button(first, text='Hello There This is 1st Tab', bg='Red')
a.pack()
b = Button(second, text='Hello There This is 2nd Tab',bg = 'coral')
b.pack()
tabs.pack(expand=1, fill="both")
mainloop()

Adding widgets in the tabs, Example

from tkinter import *
from tkinter import ttk

labelframe = Tk()
labelframe.geometry('640x300')
labelframe.title('IoT4Begineers')

tabs = ttk.Notebook(labelframe)
first = ttk.Frame(tabs)
tabs.add(first, text='First')
second = ttk.Frame(tabs)
tabs.add(second, text='Second')
a = Button(first, text='Hello There This is 1st Tab', bg='Red')
a.pack()
b = Button(second, text='Hello There This is 2nd Tab',bg = 'coral')
b.pack()
tabs.pack(expand=1, fill="both")
mainloop()


-First Tab has a button color Red and second tab has a button color coral

Well, that’s about it. Now go create something more fun, and I hope my tutorial has helped you out somewhat.

After reading this tutorial on “How to layout your GUI”, I am pretty sure you want to know more about Python. To know more about Python you can refer the following blogs:

  1. Introduction to Python
  2. Object-Oriented Programming in Python
  3. Python Flask Tutorial
  4. Plotting graphs with Matplotlib (Python)

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Tkinter based GUI- Application form

Tkinter based GUI- Application form

Hello everyone! Today we are going to make a Tkinter based GUI that will be an Application Form . We will ask some details by the user and then will be saving that with a default extension of .yaml, which can be changed at the time of saving the file. Let's go ahead!...

Look and Feel Customization on Python Tkinter

In this tutorial, you will learn about how to customize the look and feel of a python GUI created using tkinter. This is third part of tkinter tutorial course. To begin with, we will look at how to create message boxes. Contents: Creating MessageboxesCreate...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....