Python tkinter Tutorial for Class 12 Comprehensive Guide

Computer Science Class 12 Python tkinter tutorial

In this article, I will discuss Computer Science Class 12 Python tkinter Tutorial. This article helps CBSE computer science class 12 students to do interactive projects for their board practical exam with a GUI application. So here we go!

Computer Science Class 12 Python tkinter Tutorial

As a CBSE Computer Science class 12 student you know the concepts of functions, MySQL queries, and Python MySQL Interface with database connectivity. These topics can be integrated into the Python Tkinter GUI interface. So Tkinter is the most important tool for learning for CBSE Computer Science Class 12 Students.

So this article is designed for class 12 computer science students and Python beginners who are interested in GUI-based application development.

So let us begin CBSE computer science class 12 python Tkinter tutorial for the project.

What is Python tkinter?

Python Tkinter is a python standard library that offers many functions and controls to develop desktop based applications or Graphical User Interface (GUI) based applications.

The first step is you need to install the python tkinter library. To install it use pip command.

pip install tk

Creating Main window

To develop desktop applications using tkinter you need to create the main window first. To create the main window follow these steps:

  1. Import Tkinter library
  2. Instantiate an object for the main window
  3. Add controls like labels, buttons, frames, text boxes, checkboxes, radio buttons etc.
  4. Call loop() method for the main window to perform actions
from tkinter import *
main = Tk()

You can also use this code instead:

import tkinter as tk
main=tk.Tk()

The above code will create the main window as shown in the following image:

Computer Science Class 12 Python tkinter tutorial - first window
Computer Science Class 12 Python tkinter tutorial – first window

The above image shows the main window created by python tkinter library code. It provides a default icon, title and three buttons minimize, maximize and close by default.

The next step is to change the default size of the main window.

Changing the window size

To change the window size, tkinter provides geometry() method. This method requires two parameters for the height and width of the main window and the horizontal as well as vertical. The syntax is as follows:

window_object.geometry('heightxwidth+horizontal_position+vertical_position')

Example:

from tkinter import *
main = Tk()
main.geometry('600x600+250+50')

import tkinter as tk
main=tk.Tk()
main.geometry('600x600+250+50')

Output:

geometry method of tkinter computer science python tkinter tutorial
geometry method of tkinter computer science python tkinter tutorial

Creating and opening the main window on the center of the screen

Follow these steps to open the tikinter window in the middle of the screen.

  1. Get the screen width and height using the winfo_screenwidth() & winfo_screenheight() methods.
  2. Calculate the center coordinate based on the screen and window width and height.
  3. Finally, set the geometry for the root window using the geometry() method.

Observe this code:

import tkinter as tk
main=tk.Tk()
h=600
w=600

# get the screen dimension
sw = main.winfo_screenwidth()
sh = main.winfo_screenheight()

# find the center point
cx = int(sw/2 - h / 2)
cy = int(sh/2 - w / 2)

# set the position of the window to the center of the screen
main.geometry(f'600x600+{cx}+{cy}')

Output:

tkinter window in the center of the screen
tkinter window in the center of the screen

Resizing window

The main window can be resized according to height and width. It can be restricted with the help of resizable() function. This function has two boolean parameters according to height and width. Observe this code:

import tkinter as tk
main=tk.Tk()
main.geometry(600,600)
main.resizable(False,False)

Output:

Python tkinter Tutorial for Class 12 Comprehensive Guide

Specifying maximum and minimum size of main window

The tkinter main window size can be set maximum and minimum usig maxsize() and minsize() function.

main.maxsize(800,800)
main.minsize(100,100)

Changing title of main window

The default title can be changed using title() function. Observe this code:

main.title("Tkinter window Tutorial")
title of tkinter window

Watch this video tutorial for more understanding:

Setting background colour for main window

There are three ways to set a background colour for main window. They are:

  1. Using configure() function
  2. bg property
  3. background property

Using configure() function

The configure() method requires a parameter bg with a colour value. The colour value can be a colour name or colour code in hexadecimal form beginning with #.

Syntax:

window_object.configure(bg=colourname/colourcode)

Example:

#Using colour name
main.configure(bg='lightgreen')

#Using hex colour code
main.configure(bg='#2211FF')

Output:

tkinter background colour using configure method

Output:

tkinter window background using hex colour code

Using bg property

bg property can be written in the subscript bracket like list value with a value colour name and hex colour code.

Syntax:

window_object['bg']=colourname/colourcode

Example:

#using colourname
main['bg']='lightblue'

#using colourcode
main['bg']='#1122DD'

Output:

tkinter window background colour bg colour

Output (Hex Colour Code):

background colour with hex colour code

Using background property

The background property can be also used for changing the background colour. The syntax is likely similar to bg property.

Syntax:

window_object['bg']=colourname/colourcode

Example:

#using colourname
main['background']='lightblue'

#using colourcode
main['background']='#1122DD'

Changing icon Image of window

Follow these steps to change the default icon of Tkinter main window.

  1. To change the default icon of the Tkinter window, prepare an image to set as an icon.
  2. Save the image into the same folder where the python program is saved.
  3. Load the photo using PhotoImage() method into an object. The PhotoImage() method has one parameter i.e. file which requires filename.
  4. Now use iconphoto() method to change the default icon.

Observe this code:

ph=PhotoImage(file='tk.png')
main.iconphoto(False,ph)

Output:

changing default icon of tkinter window python

You can also avoid PhotoImage() method and provide only iconphoto() method in the following manner:

main.iconphoto(False,'tk.png')

Restricting window to close

main.protocol() function is used to restrict the window to be closed. Sometimes it is required to ensure that the task has been completed then only the window should be closed. Such as saving the data in the window.

The example is as follows:

main.protocol("WM_DELETE_WINDOW",main)

Changing the attributes of tkinter main window

The attributes of Tkinter main window can be changed using main.attributes() function. This function allows to transparent the window, fullscreen window, changing order on top etc. Observe the code given below:

Transparent tkinter main window:

main.attributes('-alph',0.5)

Output:

tranparent tkinter main window in python

The windows can be transparent with a range of 0.0 to 1.0, where 0.0 is fully transparent and 1.0 is fully opaque.

Fullscreen:

The tikinter main window can be expand up to fullscreen. Use this code:

main.attributes('-fullscreen',1)

Before making the window in fullscreen mode change the maxheight and maxwidth, if already applied.

Changing the window’s order:

Sometimes while working multiple windows the main Tkinter window needs to bring on top. The following code will help to bring the Tkinter main window on top.

main.attributes('-topmost',1)

Lift and lower the main window

To lift and lower the window use lift() and lower() methods respectively. This methods also help while working with multiple tkinter window. Observe the following:

main.lift()
main.lift(otherwin)
main.lower()
main.lower(otherwin)

Python Tkinter widgets

Python Tkinter widgets are the controls drawn on the main window to design desktop-based applications. These widgets are explained in the next section.

Python tkinter has 18 widgets. They are as follows:

S.NoWidgetDescription
1ButtonUsed to add a clickable command button in tkinter window
2CanvasUsed to draw a complex layout and picture, it can hold text and graphics
3CheckButtonUsed to select an option from multiple options given in the window
4EntryUsed to accept a single-line text for input
5FrameUsed to hold multiple widgets inside a frame and organize them in proper order
6LabelUsed to display a single-line caption
7ListBoxUsed to display a list of options
8MenuUsed to prepare command menus for tkinter window
9MenuButtonUsed to add a menu item in the main menu
10MessageUsed to display a message box with a message and buttons
11RadioButtonUsed to select a single option from given multiple options
12ScaleUsed to provide a scale with a slider holding list of values
13ScrollbarUsed to navigate throughout the window
14TextUsed to take input of multiple lines from the user
15ToplevelUsed to provide a top-level container
16SpinBoxUsed to accept value by selecting a fixed value of numbers
17PanedWindowUsed to handle different panes of a window
18LabelFrameUsed to handle complex widgets

Creating Widgets using Tkinter

Let us create various widgets and add them to the main window. Here we go!

Creating Command Button

The command button is a very important part of any GUI application. It allows to click itself and perform the task at runtime. To create a command button follow these steps:

  1. Use the Button class constructor with two parameters. The parameters are:
    • window – The reference of main window
    • attributes – Button attributes such as text, bg, fg, font, image and command
  2. Use the place method to place it at the appropriate place. This method accepts the horizontal and vertical coordinates in the form x and y.

Now let us see the code:

from tkinter import *
#Creating Main Window
main = Tk()
main.title("Tkinter window Tutorial- Creating Command Button")
main.geometry('600x600+250+50')
main.resizable(0, 0)
ph=PhotoImage(file='tk.png')
main.iconphoto(False,ph)

#Creating a Command Button
cmdBtn=Button(main,text='Click Me!',fg='Red',bg='Yellow')
cmdBtn.place(x=50,y=100)

Output:

Creating command button using Tkinter

Creating Label

The label is a widget of a GUI application which shows the caption to the user and make the GUI application more interactive.

To create a label the Label class constructor is required with the main window and other parameters as a command button. Let’s have look at this example:

myLbl=Label(main,text='Welcome to Python GUI World!',fg='Blue',bg='White',font=('Arial',16))
myLbl.place(x=10,y=20)

Output:

Creating a Label in Tkinter

Button Click

To do something on a button click, create a function for the same.

For example:

def onClick():
  myLbl.configure(text="Nice! You have clicked the button.")

cmdBtn=Button(main,text='Click Me!', command=onClick)

Output:

Python tkinter Tutorial for Class 12 Comprehensive Guide

Creating Entry Widget

The Entry widget allows taking input from users in a single line of text. It requires the Entry class constructor and other attributes in association with the main window.

It requires two additional parameters:

  1. bd – To display a border size of the text field, the default border is 2 pixels
  2. show – To set the text field as the password field when the show property set to ‘*’.

Let us have a look at this example:

Textfield

txtfld=Entry(window, text="This is Entry Widget", bd=5)
txtfld.place(x=80, y=150)

Output:

Creating a Textfield in Tkinter

Password Field

MyPF1=Entry(main, bd=5, show='*')
MyPF1.place(x=50, y=50)

Output:

Python tkinter Tutorial for Class 12 Comprehensive Guide

Properties of Entry widget

The entry window supports the following properties:

SNOptionDescription
1bgBackground colour
2bdThe border width of the entry field in pixels
3cursorthe mouse pointer will be changed into cursor type set to the arrow, dot, etc.
4exportselectionTo copy the text entred in the entry field. Set 0 not to copy
5fgText (Foreground) Colour
6fontFonts inside the entry field
7highlightbackgroundRepresents the color to display when the widget does not have the input focus
8highlightcolorRepresents the colour to when it has the input focus
9highlightthicknessA non-negative value indicating the width of the highlight when it has the input focus.
10insertbackgroundThe colour to use as background in the area covered by the insertion cursor. This colour will normally override either the normal background for the widget.
11insertborderwidthA non-negative value indicating the width of the 3-D border, the value may have any of the forms acceptable to Tk_GetPixels.
12insertofftimeA non-negative integer value indicating the number of milliseconds the insertion cursor should remain “off” in each blink cycle. If this option is zero, then the cursor doesn’t blink: it is on all the time.
13insertontimeSpecifies a non-negative integer value indicating the number of milliseconds the insertion cursor should remain “on” in each blink cycle.
14insertwidthIt represents the value indicating the total width of the insertion cursor. The value may have any of the forms acceptable to Tk_GetPixels.
15justifyIt specifies how the text is organized if the text contains multiple lines.
16reliefIt specifies the type of the border. Its default value is FLAT. the Possible values are: FLAT, RAISED, SUNKEN, GROOVE, RIDGE
17selectbackgroundbackground color of the selected text.
18selectborderwidthwidth of the border to display around the selected task
19selectforegroundfont color of the selected task.
20showShow the entry text of some other type instead of the string. For example, the password is typed using stars (*).
21textvariableset to the instance of the StringVar to retrieve the text from the entry
22widthwidth of the displayed text or image.
23xscrollcommandlinked to the horizontal scrollbar if we want the user to enter more text then the actual width of the widget.

Methods for entry widget

The entry widget has the following methods to configure data entered inside the entry field.

SNMethodDescription
1delete(first, last = none)Delete the specified characters inside the widget
2get()Get the text written inside the widget
3icursor(index)Change the insertion cursor position, specify the index of the character before which, the cursor is to be placed
4index(index)Place the cursor to the left of the character written at the specified index
5insert(index,s)Insert the specified string before the character is placed at the specified index
6select_adjust(index)Includes the selection of the character present at the specified index
7select_clear()Clears the selection if some selection has been done
8select_form(index)Sets the anchor index position to the character specified by the index
9select_present()Returns true if some text in the Entry is selected otherwise returns false
10select_range(start,end)Selects the characters to exist within the specified range
11select_to(index)Selects all the characters from the beginning to the specified index
12xview(index)Used to link the entry widget to a horizontal scrollbar
13xview_scroll(number,what)Used to make the entry scrollable horizontally

Working with the Entry field, labels and a button

Let us create a python Tkinter application for computing a simple interest calculator. Follow this link to learn how to design the simple interest calculator:

Tkinter Program to Compute Simple Interest

Creating Radio Button

Radio Button allows selecting a single field from given multiple options. For example, Every Student has opted only a single stream out of Science, Commerce or Humanities.

It is a toggle button which represents the On/Off state. When the user clicks the circle it will be on and if the user clicks again on the same it will be off.

It requires a RadioButton class constructor with the following two additional parameters:

  1. value – For default selection of the radio button assign value 1 to the parameter value.
  2. variable – Setting value 1 for the selection of one of the radio buttons.

Observe the code:

v=IntVar()
v.set(1)
rdo1=Radiobutton(main, text="Science", variable=v, value=1)
rdo2=Radiobutton(main, text="Commerce", variable=v, value=2)
rdo3=Radiobutton(main, text='Humanities', variable=v, value=3)
rdo1.place(x=100,y=50)
rdo2.place(x=180, y=50)
rdo3.place(x=250, y=50)

Output:

Creating Radio Buttons

Creating Checkbox

It is also a toggle button that allows selecting multiple values from the set of options provided. It is a small square box button that shows a tick mark when it’s clicked.

Have a look at this code snippet:

chk1 = Checkbutton(main, text = "Cricket")
chk2 = Checkbutton(main, text = "Tennis")
chk1.place(x=100, y=100)
chk2.place(x=180, y=100)  

Output:

creating checkbox in python using tkinter

Creating Combobox

Combobox is a widget that populates a drop-down data from a set of values. It can get the values from a tuple or list of values.

Combobox is a widget of tkinter’s ttk class. So you need to import it from ttk class.

Observe this code:

from tkinter.ttk import *
sp=['Cricket','VolleyBall','FootBall','Table Tennis']
cmb=Combobox(main,values=sp)
cmb.place(x=50,y=100)

Output:

Creating Python Tkinter Combobox

To set the default selected item Combobox.current(n) method is used. Just have a look at this code:

cmb.current(2)

Output:

Set the default item for python tkinter combobox

Creating a list box

The list box widget is a little bit different from Combobox. The main difference is list box displays the entire collection of list of items. The user can select one or multiple items.

Observe the code:

sp=['Cricket','VolleyBall','FootBall','Table Tennis','Chess']
lstBox=Listbox(main, height=5, selectmode='multiple')
for num in sp:
    lstBox.insert(END,num)
lstBox.place(x=250, y=150)

Output:

Listbox in python tkinter

So I hope you enjoyed the learnings from this article. Now you can create GUI-based windows in Python. Thank you for reading this article.