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!
Topics Covered
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:
- Import Tkinter library
- Instantiate an object for the main window
- Add controls like labels, buttons, frames, text boxes, checkboxes, radio buttons etc.
- 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:
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:
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.
- Get the screen width and height using the
winfo_screenwidth()
&winfo_screenheight()
methods. - Calculate the center coordinate based on the screen and window width and height.
- 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:
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:
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")
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:
- Using configure() function
- bg property
- 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:
Output:
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:
Output (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.
- To change the default icon of the Tkinter window, prepare an image to set as an icon.
- Save the image into the same folder where the python program is saved.
- Load the photo using PhotoImage() method into an object. The PhotoImage() method has one parameter i.e. file which requires filename.
- Now use iconphoto() method to change the default icon.
Observe this code:
ph=PhotoImage(file='tk.png')
main.iconphoto(False,ph)
Output:
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:
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.No | Widget | Description |
1 | Button | Used to add a clickable command button in tkinter window |
2 | Canvas | Used to draw a complex layout and picture, it can hold text and graphics |
3 | CheckButton | Used to select an option from multiple options given in the window |
4 | Entry | Used to accept a single-line text for input |
5 | Frame | Used to hold multiple widgets inside a frame and organize them in proper order |
6 | Label | Used to display a single-line caption |
7 | ListBox | Used to display a list of options |
8 | Menu | Used to prepare command menus for tkinter window |
9 | MenuButton | Used to add a menu item in the main menu |
10 | Message | Used to display a message box with a message and buttons |
11 | RadioButton | Used to select a single option from given multiple options |
12 | Scale | Used to provide a scale with a slider holding list of values |
13 | Scrollbar | Used to navigate throughout the window |
14 | Text | Used to take input of multiple lines from the user |
15 | Toplevel | Used to provide a top-level container |
16 | SpinBox | Used to accept value by selecting a fixed value of numbers |
17 | PanedWindow | Used to handle different panes of a window |
18 | LabelFrame | Used 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:
- 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
- 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 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:
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:
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:
- bd – To display a border size of the text field, the default border is 2 pixels
- 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:
Password Field
MyPF1=Entry(main, bd=5, show='*')
MyPF1.place(x=50, y=50)
Output:
Properties of Entry widget
The entry window supports the following properties:
SN | Option | Description |
---|---|---|
1 | bg | Background colour |
2 | bd | The border width of the entry field in pixels |
3 | cursor | the mouse pointer will be changed into cursor type set to the arrow, dot, etc. |
4 | exportselection | To copy the text entred in the entry field. Set 0 not to copy |
5 | fg | Text (Foreground) Colour |
6 | font | Fonts inside the entry field |
7 | highlightbackground | Represents the color to display when the widget does not have the input focus |
8 | highlightcolor | Represents the colour to when it has the input focus |
9 | highlightthickness | A non-negative value indicating the width of the highlight when it has the input focus. |
10 | insertbackground | The 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. |
11 | insertborderwidth | A non-negative value indicating the width of the 3-D border, the value may have any of the forms acceptable to Tk_GetPixels. |
12 | insertofftime | A 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. |
13 | insertontime | Specifies a non-negative integer value indicating the number of milliseconds the insertion cursor should remain “on” in each blink cycle. |
14 | insertwidth | It represents the value indicating the total width of the insertion cursor. The value may have any of the forms acceptable to Tk_GetPixels. |
15 | justify | It specifies how the text is organized if the text contains multiple lines. |
16 | relief | It specifies the type of the border. Its default value is FLAT. the Possible values are: FLAT, RAISED, SUNKEN, GROOVE, RIDGE |
17 | selectbackground | background color of the selected text. |
18 | selectborderwidth | width of the border to display around the selected task |
19 | selectforeground | font color of the selected task. |
20 | show | Show the entry text of some other type instead of the string. For example, the password is typed using stars (*). |
21 | textvariable | set to the instance of the StringVar to retrieve the text from the entry |
22 | width | width of the displayed text or image. |
23 | xscrollcommand | linked 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.
SN | Method | Description |
---|---|---|
1 | delete(first, last = none) | Delete the specified characters inside the widget |
2 | get() | Get the text written inside the widget |
3 | icursor(index) | Change the insertion cursor position, specify the index of the character before which, the cursor is to be placed |
4 | index(index) | Place the cursor to the left of the character written at the specified index |
5 | insert(index,s) | Insert the specified string before the character is placed at the specified index |
6 | select_adjust(index) | Includes the selection of the character present at the specified index |
7 | select_clear() | Clears the selection if some selection has been done |
8 | select_form(index) | Sets the anchor index position to the character specified by the index |
9 | select_present() | Returns true if some text in the Entry is selected otherwise returns false |
10 | select_range(start,end) | Selects the characters to exist within the specified range |
11 | select_to(index) | Selects all the characters from the beginning to the specified index |
12 | xview(index) | Used to link the entry widget to a horizontal scrollbar |
13 | xview_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:
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:
- value – For default selection of the radio button assign value 1 to the parameter value.
- 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 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 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:
To set the default selected item Combobox.current(n) method is used. Just have a look at this code:
cmb.current(2)
Output:
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:
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.