0% found this document useful (0 votes)
91 views71 pages

Tkinter

Uploaded by

Krit Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views71 pages

Tkinter

Uploaded by

Krit Chaudhary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Tkinter

Mr. Harendra Sharma


Assistant Professor
SRM University (Delhi NCR Campus)

Harendra Sharma (Assistanat Professor)


Harendra Sharma (Assistanat Professor)
Harendra Sharma (Assistanat Professor)
GUI Programming in Python
There are many ways to develop GUI based programs in
Python. These different ways are given below:

Tkinter:
• In Python, Tkinter is a standard GUI (graphical user interface) package.
Tkinter is Python's default GUI module and also the most common way
that is used for GUI programming in Python. Note that Tkinter is a set
of wrappers that implement the Tk widgets as Python classes.

wxPython:
• This is basically an open-source, cross-platform GUI toolkit that is
written in C++. Also an alternative to Tkinter.

JPython:
• JPython is a Python platform for Java that is providing Python scripts
seamless access to Java class Libraries for the local machine.

Harendra Sharma (Assistanat Professor)


Harendra Sharma (Assistanat Professor)
Harendra Sharma (Assistanat Professor)
What is Tkinter
• Tkinter in Python helps in creating
GUI Applications with a minimum hassle.
Among various GUI Frameworks, Tkinter is
the only framework that is built-in
into Python's Standard Library.
• An important feature in favor of Tkinter is that
it is cross-platform, so the same code can
easily work on Windows, macOS, and Linux.
• Tkinter is a lightweight module.
• It is simple to use.
Harendra Sharma (Assistanat Professor)
What are Tcl, Tk, and Tkinter
• Let's try to understand more about the Tkinter module by discussing
more about it origin.
• As mentioned, Tkinter is Python's default GUI library, which is
nothing but a wrapper module on top of the Tk toolkit.
• Tkinter is based upon the Tk toolkit, and which was originally
designed for the Tool Command Language (Tcl). As Tk is very
popular thus it has been ported to a variety of other scripting
languages, including Perl (Perl/Tk), Ruby (Ruby/Tk), and Python
(Tkinter).
• GUI development portability and flexibility of Tk makes it the right
tool which can be used to design and implement a wide variety of
commercial-quality GUI applications.
• Python with Tkinter provides us a faster and efficient way in order
to build useful applications that would have taken much time if you
had to program directly in C/C++ with the help of native OS system
libraries.
• Once we have Tkinter up and running, we'll use basic building
blocks known as widgets to create a variety of desktop applications.
Harendra Sharma (Assistanat Professor)
Harendra Sharma (Assistanat Professor)
Harendra Sharma (Assistanat Professor)
First Tkinter Example
• As mentioned earlier that in GUI programming
all main widgets are only built on the top-level
window object.
• The top-level window object is created by
the Tk class in Tkinter.
import tkinter as tk
win = tk.Tk()
win.mainloop()

Harendra Sharma (Assistanat Professor)


Tkinter Methods used back:

The two main methods are used while creating the Python
application with GUI. You must need to remember them and
these are given below:
1. Tk(screenName=None,baseName=None,className='Tk',
useTk=1)
• This method is mainly used to create the main window.
You can also change the name of the window if you want,
just by changing the className to the desired one.
• The code used to create the main window of the
application is and we have also used it in our above example:
win = tkinter.Tk() ## where win indicates name of the main
window object
Harendra Sharma (Assistanat Professor)
2. The mainloop() Function

This method is used to start the application.


The mainloop() function is an infinite
loop which is used to run the application, it
will wait for an event to occur and process the
event as long as the window is not closed.

Harendra Sharma (Assistanat Professor)


Tkinter Windows, Widgets and
Frames

Harendra Sharma (Assistanat Professor)


• The top-level window object in GUI Programming contains
all of the little window objects that will be part of your
complete GUI.
• The little window objects can be text labels, buttons, list
boxes, etc., and these individual little GUI components are
known as Widgets.
• So, having a top-level window object will act as a container
where you will put all your widgets. In Python, you'd
typically do so like this using the following code: win =
tkinter.Tk()
• The object that is returned by making a call to tkinter.Tk() is
usually referred to as the Root Window.
• Top-level windows are mainly stand-alone as part of your
application, also you can have more than one top-level
window for your GUI, but only one of them should be
your root window.

Harendra Sharma (Assistanat Professor)


• First of all, you need to design all your widgets
completely, and then add the real functionality.
• The widgets can either be stand-alone or can
be containers. If one widget contains other widgets, it is
considered the parent of those widgets.
• Similarly, if a widget is contained within another
widget, it's known as a child of the parent, the parent is
the next immediate enclosing container widget.
• The widgets also have some associated behaviors, such
as when a button is pressed, or text is filled into a text
field, so we have events attached to these actions.
• The behavior of widgets generates events, and
the GUI's response to events is known as Callbacks -
because they 'call' a function just to handle the
event that occurred.

Harendra Sharma (Assistanat Professor)


Tkinter Event-Driven Processing
• In Tkinter, we have windows and widgets
coming together to form a GUI application.
But the GUI application is just the frontend of
the application. You would want to execute
some code logic when the end-user uses those
widgets.
• Whenever an action is performed on any
widget, an event is generated, which we can
handle to perform any operation.

Harendra Sharma (Assistanat Professor)


• Events(behavior of widgets) can include pressing a
button, movement of the mouse, hitting the return or Enter
key, gaining or losing 'focus', etc.

• The entire system of events that occurs from the beginning


until the end of any GUI application is what drives it and
hence it is also known as Event-Driven Processing.

• Let us take a simple mouse movement example: Suppose


that the pointer of the mouse is just sitting somewhere on
top of your GUI application. If you will move the mouse to
another part of your application, something has to cause the
movement of the mouse to be replicated by the cursor on
your screen(on top of your GUI application). These
are 'cursor move' events that the system must process to
portray your cursor moving across the window. At the time
you will stop moving the mouse, no more events need to be
processed, so everything just stays still on the screen again.
Harendra Sharma (Assistanat Professor)
Tkinter Windows
The term "Window" has different meanings in the
different contexts, But generally "Window" refers
to a rectangular area somewhere on the user‘s
display screen through which you can interact.

Tkinter Top-Level Window


The Top-Level Window is a window that exists
independently on the screen. You can decorate the
top-level window with the standard frame and
controls for the desktop manager. It can usually be
moved around the desktop, and also you can
resize it if you want to do so.
Harendra Sharma (Assistanat Professor)
Tkinter Widgets
The term "Widgets" is a generic term that refers to the building blocks
that make up an application in a graphical user interface.

Let us list out the core widgets with their categories:


• Container
Under this category, the widgets that lies are frame, labelframe,
toplevel, and paned window.
• Buttons
Under the category of Buttons, there are buttons, radiobuttons,
checkbuttons (checkbox), and menubuttons.
• Text Widgets
Under the category of text widgets, there are labels, messages, text.
• Entry Widgets
Under this category, the widgets are scale, scrollbar, Listbox, slider,
spinbox, entry (single-line), optionmenu, text (multiline), and
canvas (vector and pixel graphics).

Harendra Sharma (Assistanat Professor)


Tkinter Frames
• A frame is basically a rectangular area that can
contain other widgets. In Tkinter, there is a Frame
widget that is the basic unit of organization for
complex layouts. It is a widget which has no
special styling or GUI component of its own. It is
just used to hold other Tkinter widgets in case of
complex GUI layouts.
• Note: It is important to note here that whenever
any widget is created, there is also a parent-child
relationship that is created. Just take an example,
if you place a button inside a frame, the frame
widget is called the parent of the Button widget.
Harendra Sharma (Assistanat Professor)
Tkinter Basic Example

from tkinter import *


win = Tk() # Create the root (base) window
win.geometry("200x200")
w = Label(win, text="Hello, Welcome to GUI")
# Create a label with words
w.pack() # Put the label into the window
win.mainloop() # Start the event loop

Harendra Sharma (Assistanat Professor)


Widgets
Tkinter provides various controls, such as
buttons, labels and text boxes used in a GUI
application. These controls are commonly
called Widgets. The list of commonly
used Widgets are mentioned below –

Label : The Label widget is used to provide a


single-line caption for other widgets. It can
also contain images.
Button The Button widget is used to display
buttons in your application.
Harendra Sharma (Assistanat Professor)
EntryThe Entry widget is used to display a
single-line text field for accepting values from
a user.
MenuThe Menu widget is used to provide
various commands to a user. These commands
are contained inside Menubutton.
CanvasThe Canvas widget is used to draw
shapes, such as lines, ovals, polygons and
rectangles, in your application.
CheckbuttonThe Checkbutton widget is used to
display a number of options as checkboxes.
The user can select multiple options at a time.
Harendra Sharma (Assistanat Professor)
FrameThe Frame widget is used as a container
widget to organize other widgets.
ListboxThe Listbox widget is used to provide a
list of options to a user.
MenubuttonThe Menubutton widget is used to
display menus in your application.
MessageThe Message widget is used to display
multiline text fields for accepting values from
a user.
RadiobuttonThe Radiobutton widget is used to
display a number of options as radio buttons.
The user can select only one option at a time.
Harendra Sharma (Assistanat Professor)
ScaleThe Scale widget is used to provide a slider
widget.
ScrollbarThe Scrollbar widget is used to add
scrolling capability to various widgets, such as list
boxes.
TextThe Text widget is used to display text in
multiple lines.
ToplevelThe Toplevel widget is used to provide a
separate window container.
LabelFrameA labelframe is a simple container
widget. Its primary purpose is to act as a spacer or
container for complex window layouts.
Harendra Sharma (Assistanat Professor)
tkMessageBoxThis module is used to display
message boxes in your applications.

SpinboxThe Spinbox widget is a variant of the


standard Tkinter Entry widget, which can be
used to select from a fixed number of values.

PanedWindowA PanedWindow is a container


widget that may contain any number of panes,
arranged horizontally or vertically.

Harendra Sharma (Assistanat Professor)


Geometry Management
All Tkinter widgets have access to specific
geometry management methods, which have
the purpose of organizing widgets throughout
the parent widget area. Tkinter exposes the
following geometry manager classes: pack,
grid, and place. Their description is mentioned
below –
pack()This geometry manager organizes widgets
in blocks before placing them in the parent
widget.
Harendra Sharma (Assistanat Professor)
grid()This geometry manager organizes widgets
in a table-like structure in the parent widget.

place()This geometry manager organizes


widgets by placing them in a specific position
in the parent widget.

Harendra Sharma (Assistanat Professor)


Hello World in Tkinter
from tkinter import *
In Python3 firstly we import all the classes, functions and variables
from the tkinter package.

root=Tk()
Now we create a root widget, by calling the Tk(). This automatically
creates a graphical window with the title bar, minimize, maximize
and close buttons. This handle allows us to put the contents in the
window and reconfigure it as necessary.

a = Label(root, text="Hello, world!")


Now we create a Label widget as a child to the root window. Here
root is the parent of our label widget. We set the default text to
“Hello, World!”

Note: This gets displayed in the window. A Label widget can display
either text or an icon or other image.

Harendra Sharma (Assistanat Professor)


Details of Widgets

Button
• Tkinter is a Python standard library that is used to create
GUI (Graphical User Interface) applications.
• It is one of the most commonly used packages of Python.
• Tkinter supports both traditional and modern graphics
support with the help of Tk themed widgets.
• All the widgets that tkinter has also available in tkinter.ttk.
• Adding style in a tkinter.ttk button is little creepy because it
doesn’t support direct implementation.
• To add styling in a ttk.Button we have to first create a object
of style class which is available in tkinter.ttk.
We can create ttk.Button by using the following steps:

Harendra Sharma (Assistanat Professor)


btn = ttk.Button(master, option = value, ...)

ttk.Button options –
command: A function to be called when button is
pressed.
text: Text which appears on the Button.
image: Image to be appeared on the Button.
style: Style to be used in rendering this button.

To add styling on the ttk.Button we cannot


directly pass the value in the options. Firstly, we
have to create a Style object which can be created
as follows:
style = ttk.Style()
Harendra Sharma (Assistanat Professor)
a.pack()
Next, we call the pack() method on this widget. This tells it to size itself to
fit the given text, and make itself visible. It just tells the geometry
manager to put widgets in the same row or column. It’s usually the easiest
to use if you just want one or a few widgets to appear.

root.mainloop()
The application window does not appear before you enter the main loop.
This method says to take all the widgets and objects we created, render
them on our screen, and respond to any interactions. The program stays in
the loop until we close the window.

from tkinter import *


root = Tk()
a = Label(root, text ="Hello World")
a.pack()
root.mainloop()
Harendra Sharma (Assistanat Professor)
Creating a button
from tkinter import * # import everything from tkinter module
root = Tk() # create a tkinter window
root.geometry('100x100') # Open window having dimension 100x100
# Create a Button
btn = Button(root, text = 'Click me !', bd = '5‘,command = root.destroy)
# Set the position of button on the top of window.
btn.pack(side = 'top')
root.mainloop()

Harendra Sharma (Assistanat Professor)


from tkinter import *
from tkinter.ttk import *
root = Tk()
root.geometry('100x100')
style = ttk.Style() # This will create style object
# This will be adding style, and naming that style variable as W.Tbutton (TButton
is used for ttk.Button).
style.configure('W.TButton', font = ('calibri', 10, 'bold', 'underline'), foreground =
'red')
# Style will be reflected only on this button because we are providing style only on
this Button.
btn1 = Button(root, text = 'Quit !', style = 'W.TButton‘,command = root.destroy)
btn1.grid(row = 0, column = 3, padx = 100)
btn2 = Button(root, text = 'Click me !', command = None)
btn2.grid(row = 1, column = 3, pady = 10, padx = 100)
root.mainloop()

Harendra Sharma (Assistanat Professor)


from tkinter import *
from tkinter.ttk import *
root = Tk()
root.geometry('100x100')
style = Style() # Create style Object
# Will add style to every available button even though we are not passing style to
every button widget.
style.configure('TButton', font = ('calibri', 10, 'bold', 'underline'),foreground = 'red')
btn1 = Button(root, text = 'Quit !', style = 'TButton‘, command = root.destroy)
btn1.grid(row = 0, column = 3, padx = 100)
btn2 = Button(root, text = 'Click me !', command = None)
btn2.grid(row = 1, column = 3, pady = 10, padx = 100)
root.mainloop()

Harendra Sharma (Assistanat Professor)


from tkinter import *
from tkinter.ttk import *
root = Tk()
root.geometry('500x500')
style = Style() # Create style Object
style.configure('TButton', font = ('calibri', 20, 'bold'), borderwidth = '4')
# Changes will be reflected by the movement of mouse.
style.map('TButton', foreground = [('active', '! disabled', 'green')], background =
[('active', 'black')])
btn1 = Button(root, text = 'Quit !', command = root.destroy)
btn1.grid(row = 0, column = 3, padx = 100)
btn2 = Button(root, text = 'Click me !', command = None)
btn2.grid(row = 1, column = 3, pady = 10, padx = 100)
root.mainloop()

Harendra Sharma (Assistanat Professor)


PhotoImage()
• Tkinter is a Python module which is used to create GUI
(Graphical User Interface) applications with the help of
varieties of widgets and functions. Like any other GUI
module it also supports images i.e you can use images
in the application to make it more attractive.
• Image can be added with the help
of PhotoImage() method. This is a Tkinter method
which means you don’t have to import any other
module in order to use it.
• Important: If both image and text are given on Button,
the text will be dominated and only image will appear
on the Button. But if you want to show both image and
text then you have to pass compound in button options.

Harendra Sharma (Assistanat Professor)


• Button(master, text = "Button", image = "image.png",
compound=LEFT)

compound = LEFT -> image will be at left side of the button


compound = RIGHT -> image will be at right side of button
compound = TOP -> image will be at top of button
compound = BOTTOM -> image will be at bottom of button

Syntax:
photo = PhotoImage(file = "path_of_file")
path_of_file is any valid path available on your local
machine.

Harendra Sharma (Assistanat Professor)


Example

from tkinter import *


from tkinter.ttk import *
root = Tk()
# Adding widgets to the root window
Label(root, text = ‘Welcome to SRM‘, font=('Verdana',5))
.pack(side = TOP, pady = 10)
# Creating a photoimage object to use image
photo = PhotoImage(file = r"C:\Gfg\circle.png")
# here, image option is used to set image on button
Button(root, text = 'Click Me !', image = photo).pack(side
= TOP)
mainloop()
Harendra Sharma (Assistanat Professor)
 Label

• Tkinter Label is a widget that is used to


implement display boxes where you can place
text or images.
• The text displayed by this widget can be changed
by the developer at any time you want.
• It is also used to perform tasks such as to
underline the part of the text and span the text
across multiple lines.
• It is important to note that a label can use only
one font at a time to display text. To use a label,
you just have to specify what to display in it (this
can be text, a bitmap, or an image).
Harendra Sharma (Assistanat Professor)
Syntax:
w = Label ( master, option, … )

 Parameters:
• master: This represents the parent window
• options: Below is the list of most commonly used options for this
widget. These options can be used as key-value pairs separated by
commas:

 Various Options are:


• anchor: This options is used to control the positioning of the text if
the widget has more space than required for the text. The default is
anchor=CENTER, which centers the text in the available space.
• bg: This option is used to set the normal background clior displayed
behind the label and indicator.
• height: This option is used to set the vertical dimension of the new
frame.

Harendra Sharma (Assistanat Professor)


• width:Width of the label in characters (not pixels!). If this option is
not set, the label will be sized to fit its contents.
• bd:This option is used to set the size of the border around the
indicator. Default bd value is set on 2 pixels.
• font:If you are displaying text in the label (with the text or
textvariable option), the font option is used to specify in what font
that text in the label will be displayed.
• cursor:It is used to specify what cursor to show when the mouse is
moved over the label. The default is to use the standard cursor.
• textvariable: As the name suggests it is associated with a Tkinter
variable (usually a StringVar) with the label. If the variable is
changed, the label text is updated.
• bitmap:It is used to set the bitmap to the graphical object specified
so that, the label can represent the graphics instead of text.
• fg:The label clior, used for text and bitmap labels. The default is
system specific. If you are displaying a bitmap, this is the clior that
will appear at the position of the 1-bits in the bitmap.
Harendra Sharma (Assistanat Professor)
• image: This option is used to display a static image in the label
widget.
• padx:This option is used to add extra spaces between left and right
of the text within the label.The default value for this option is 1.
• pady:This option is used to add extra spaces between top and
bottom of the text within the label.The default value for this option
is 1.
• justify:This option is used to define how to align multiple lines of
text. Use LEFT, RIGHT, or CENTER as its values. Note that to
position the text inside the widget, use the anchor option. Default
value for justify is CENTER.
• relief: This option is used to specify appearance of a decorative
border around the label. The default value for this option is FLAT.
• underline:This
• wraplength:Instead of having only one line as the label text it can
be broken itno to the number of lines where each line has the
number of characters specified to this option.
Harendra Sharma (Assistanat Professor)
Example

from tkinter import *


top = Tk()
top.geometry("450x300")
# the label for user_name
user_name = Label(top, text = "Username").place(x = 40, y = 60)
# the label for user_password
user_password = Label(top, text = "Password").place(x = 40, y = 100)
submit_button = Button(top, text = "Submit").place(x = 40, y = 130)
user_name_input_area = Entry(top, width = 30).place(x = 110, y = 60)
user_password_entry_area = Entry(top, width = 30).place(x = 110, y = 100)
top.mainloop()

Harendra Sharma (Assistanat Professor)


 RadioButton

• The Radiobutton is a standard Tkinter widget used to implement


one-of-many selections.
• Radiobuttons can contain text or images, and you can associate a
Python function or method with each button.
• When the button is pressed, Tkinter automatically calls that function
or method.

Syntax:
button = Radiobutton(master, text=”Name on Button”, variable =
“shared variable”, value = “values of each button”, options =
values, …)

shared variable = A Tkinter variable shared among all Radio buttons


value = each radiobutton should have different value otherwise more
than 1 radiobutton will get selected.

Harendra Sharma (Assistanat Professor)


Example
from tkinter import *
from tkinter.ttk import *
master = Tk()
master.geometry("175x175")
# Tkinter string variable able to store any string value
v = StringVar(master, "1")
# Dictionary to create multiple buttons
values = {"RadioButton 1" : "1",
"RadioButton 2" : "2",
"RadioButton 3" : "3",
"RadioButton 4" : "4",
"RadioButton 5" : "5"}
# Loop is used to create multiple Radiobuttons
# rather than creating each button separately
for (text, value) in values.items():
Radiobutton(master, text = text, variable = v, value = value).pack(side = TOP, ipady
= 5)
# Infinite loop can be terminated by keyboard or mouse interrupt or by any predefined
function (destroy())
mainloop()
Harendra Sharma (Assistanat Professor)
 Checkbutton

• The Checkbutton widget is a standard Tkinter widget that is


used to implement on/off selections.
• Checkbuttons can contain text or images. When the button
is pressed, Tkinter calls that function or method.

Syntax:
w = Checkbutton ( master, options)

Parameters:
• master: This parameter is used to represents the parent
window.
• options:There are many options which are available and
they can be used as key-value pairs separated by commas.

Harendra Sharma (Assistanat Professor)


Options: Following are commonly used Option can be used
with this widget :-

• activebackground: This option used to represent the


background color when the checkbutton is under the cursor.
• activeforeground: This option used to represent the
foreground color when the checkbutton is under the cursor.
• bg: This option used to represent the normal background
color displayed behind the label and indicator.
• bitmap: This option used to display a monochrome image
on a button.
• bd: This option used to represent the size of the border
around the indicator and the default value is 2 pixels.
• command: This option is associated with a function to be
called when the state of the checkbutton is changed.

Harendra Sharma (Assistanat Professor)


• cursor: By using this option, the mouse cursor will change to that
pattern when it is over the checkbutton.
• disabledforeground: The foreground color used to render the text of a
disabled checkbutton. The default is a stippled version of the default
foreground color.
• font: This option used to represent the font used for the text.
• fg: This option used to represent the color used to render the text.
• height: This option used to represent the number of lines of text on the
checkbutton and it’s default value is 1.
• highlightcolor: This option used to represent the color of the focus
highlight when the checkbutton has the focus.
• image: This option used to display a graphic image on the button.
• justify: This option used to control how the text is justified: CENTER,
LEFT, or RIGHT.
• offvalue: The associated control variable is set to 0 by default if the
button is unchecked. We can change the state of an unchecked variable
to some other one. Harendra Sharma (Assistanat Professor)
• onvalue: The associated control variable is set to 1 by default if the button
is checked. We can change the state of the checked variable to some other
one.
• padx: This option used to represent how much space to leave to the left
and right of the checkbutton and text. It’s default value is 1 pixel.
• pady: This option used to represent how much space to leave above and
below the checkbutton and text. It’s default value is 1 pixel.
• relief: The type of the border of the checkbutton. It’s default value is set to
FLAT.
• selectcolor: This option used to represent the color of the checkbutton
when it is set. The Default is selectcolor=”red”.
• selectimage: The image is shown on the checkbutton when it is set.
• state: It represents the state of the checkbutton. By default, it is set to
normal. We can change it to DISABLED to make the checkbutton
unresponsive. The state of the checkbutton is ACTIVE when it is under
focus.
• text: This option used use newlines (“\n”) to display multiple lines of text.
• underline: This option used to represent the index of the character in the
text which is to be underlined. The indexing starts with zero in the text.
Harendra Sharma (Assistanat Professor)
• variable: This option used to represents the associated variable that
tracks the state of the checkbutton.
• width: This option used to represents the width of the checkbutton.
and also represented in the number of characters that are represented
in the form of texts.
• wraplength: This option will be broken text into the number of
pieces.

Methods: Methods used in this widgets are as follows:

• deselect(): This method is called to turn off the checkbutton.


• flash(): The checkbutton is flashed between the active and normal
colors.
• invoke(): This method will invoke the method associated with the
checkbutton.
• select(): This method is called to turn on the checkbutton.
• toggle(): This method is used to toggle between the different
Checkbuttons.

Harendra Sharma (Assistanat Professor)


Example:
from tkinter import *
root = Tk()
root.geometry("300x200")
w = Label(root, text =‘SRM', font = "50")
w.pack()
Checkbutton1 = IntVar()
Checkbutton2 = IntVar()
Checkbutton3 = IntVar()
Button1 = Checkbutton(root, text = "Tutorial", variable = Checkbutton1, onvalue = 1,
offvalue = 0, height = 2,width = 10)
Button2 = Checkbutton(root, text = "Student", variable = Checkbutton2, onvalue = 1,
offvalue = 0, height = 2,width = 10)
Button3 = Checkbutton(root, text = "Courses", variable = Checkbutton3, onvalue = 1,
offvalue = 0, height = 2,width = 10)
Button1.pack()
Button2.pack()
Button3.pack()
Harendra Sharma (Assistanat Professor)
mainloop()
 Canvas
• The Canvas widget lets us display various graphics on the application.
• It can be used to draw simple shapes to complicated graphs.
• We can also display various kinds of custom widgets according to our
needs.

Syntax:
C = Canvas(root, height, width, bd, bg, ..)

Optional parameters
• root = root window.
• height = height of the canvas widget.
• width = width of the canvas widget.
• bg = background colour for canvas.
• bd = border of the canvas window.
Harendra Sharma (Assistanat Professor)
• scrollregion (w, n, e, s)tuple defined as a region for scrolling left, top,
bottom and right
• highlightcolor colour shown in the focus highlight.
• cursor It can defind as a cursor for the canvas which can be a circle, a do,
an arrow etc.
• confine decides if canvas can be accessed outside the scroll region.
• relief type of the border which can be SUNKEN, RAISED, GROOVE and
RIDGE.

Some common drawing methods


• Creating an Oval oval = C.create_oval(x0, y0, x1, y1, options)
• Creating an arc arc = C.create_arc(20, 50, 190, 240, start=0, extent=110,
fill="red")
• Creating a Line line = C.create_line(x0, y0, x1, y1, ..., xn, yn, options)
• Creating a polygon oval = C.create_polygon(x0, y0, x1, y1, ...xn, yn,
options)

Harendra Sharma (Assistanat Professor)


Example

from tkinter import *


root = Tk()
C = Canvas(root, bg ="yellow", height = 250, width = 300)
line = C.create_line(108, 120,320, 40, fill ="green")
arc = C.create_arc(180, 150, 80, 210, start = 0, extent = 220, fill ="red")
oval = C.create_oval(80, 30, 140, 150, fill ="blue")
C.pack()
top.mainloop()

Harendra Sharma (Assistanat Professor)


 Canvas.move()
• Canvas class of Tkinter supports a functions which is
used to move objects from one position to another in
any canvas or tkinter toplevel.
Syntax: Canvas.move(canvas_object, x, y)

Parameters
canvas_object is any valid image or drawing created
with the help of Canvas class.
x is horizontal distance from upper-left corner.
y is vertical distance from upper-left corner.

We will use class to see the working


of move() method.

Harendra Sharma (Assistanat Professor)


Class parameters-
• Data members used:
master
x
y
canvas
rectangle
• Member functions used:
movement()
left()
right()
up()
down()
• Widgets used: Canvas
• Tkinter method used:
Canvas.create_rectangle()
pack()
Canvas.move()
after()
bind()

Harendra Sharma (Assistanat Professor)


 Combobox

• Combobox is a combination of Listbox and an entry field.


• It is one of the Tkinter widgets where it contains a down
arrow to select from a list of options.
• It helps the users to select according to the list of options
displayed.
• When the user clicks on the drop-down arrow on the entry
field, a pop up of the scrolled Listbox is displayed down the
entry field.
• The selected option will be displayed in the entry field only
when an option from the Listbox is selected.

Syntax:
combobox = ttk.Combobox(master, option=value, ...)

Harendra Sharma (Assistanat Professor)


Example
import tkinter as tk
from tkinter import ttk
window = tk.Tk()
window.title('Combobox')
window.geometry('500x250')
# label text for title
ttk.Label(window, text = "GFG Combobox Widget", background = 'green', foreground
="white",
font = ("Times New Roman", 15)).grid(row = 0, column = 1)
# label
ttk.Label(window, text = "Select the Month :", font = ("Times New Roman",
10)).grid(column = 0, row = 5, padx = 10, pady = 25)
# Combobox creation
n = tk.StringVar()
monthchoosen = ttk.Combobox(window, width = 27, textvariable = n)
# Adding combobox drop down list
monthchoosen['values'] = (' January', ' February', ' March', ' April', ' May', ' June', ' July',
' August', 'September', ' October', ' November', ' December')
monthchoosen.grid(column = 1, row = 5)
monthchoosen.current()
window.mainloop()
Harendra Sharma (Assistanat Professor)
 maxsize()
• This method is used to set the maximum size of the root window (maximum size a
window can be expanded).
• User will still be able to shrink the size of the window to the minimum possible.

Syntax :
master.maxsize(height, width) Here, height and width are in pixels.

Example
from tkinter import *
from tkinter.ttk import *
from time import strftime
root = Tk()
# Fixing the size of the root window.
root.maxsize(200, 200)
# Adding widgets to the root window
Label(root, text = ‘Welcome to SRM, font =('Verdana', 15)).pack(side = TOP, pady =
10)
Button(root, text = 'Click Me !').pack(side = TOP)
mainloop()
Harendra Sharma (Assistanat Professor)
 minsize()
• In Tkinter, minsize() method is used to set the minimum size of
the Tkinter window.
• Using this method user can set window’s initialized size to its minimum size, and
still be able to maximize and scale the window larger.

Syntax:
master.minsize(height, width) Here, height and width are in pixels.

Example
from tkinter import *
from tkinter.ttk import *
from time import strftime
root = Tk()
# setting the minimum size of the root window
root.minsize(150, 100)
# Adding widgets to the root window
Label(root, text = ‘Welcome to SRM',font =('Verdana', 15)).pack(side = TOP, pady =
10)
Button(root, text = 'Click Me !').pack(side = TOP)
mainloop()
Harendra Sharma (Assistanat Professor)
Countdown Timer Using Python
Approach
We will be using the time module and its sleep() function.
Step 1: Import the time module.
Step 2: Then ask the user to input the length of the countdown in seconds.
Step 3: This value is sent as a parameter ‘t’ to the user-defined
function countdown(). Any variable read using the input function is a
string. So, convert this parameter to ‘int’ as it is of string type.
Step 4: In this function, a while loop runs until time becomes 0.
Step 5: Use divmod() to calculate the number of minutes and seconds. You
can read more about it here.
Step 6: Now print the minutes and seconds on the screen using the
variable timeformat.
Step 7: Using end = ‘\r’ we force the cursor to go back to the start of the
screen (carriage return) so that the next line printed will overwrite the
previous one.
Step 8: The time.sleep() is used to make the code wait for one sec.
Step 9: Now decrement time so that the while loop can converge.
Step 10: After the completion of the loop, we will print “Fire in the hole”
to signify the end of the countdown.

Harendra Sharma (Assistanat Professor)


# import the time module
import time
# define the countdown func.
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
print('Fire in the hole!!')
# input time in seconds
t = input("Enter the time in seconds: ")
# function call
countdown(int(t))
Harendra Sharma (Assistanat Professor)
Implement Keyboard and Mouse click event in tkinter

• Whenever we use Tkinter, we are not just limited to bind


one function to one widget.
• With widgets, we can bind multiple events to it depending
on what we do with that widget, it behaves in different kind
of ways.
• We can have a button, and if we left click it, something
happens and if you right click it, something else happens.
• Tkinter also lets you install callable to call back when
needed to handle a variety of events. However, Tkinterdoes
not let you create your own custom events; you are limited
to working with events predefined by Tkinter itself.
• Tkinter provides a powerful mechanism to let you deal with
events yourself. For each widget, you can bind Python
functions and methods to events.
widget.bind(event, handler)
Harendra Sharma (Assistanat Professor)
• If an event matching the event description occurs in the
widget, the given handler is called with an object
describing the event.
1- The Event Object: General event callbacks must
accept one argument event that is a Tkinter event
object. Such an event object has several attributes
describing the event:
widget, x_root , y_root, x, y, num, keysym, char
2- Binding Callbacks to Events:
Usually enclosed in angle brackets ('<...>')
3- Event Names: Frequently used event names, which
are almost all enclosed in angle brackets, fall into a few
categories.

1-Keyboard events
2-Mouse event,
Harendra Sharma (Assistanat Professor)
Keyboard Event:
Key, Special keys, Normal keys, Button-1, Button-2,
Button-3,B1-Motion,B2-Motion,B3-Motion,
ButtonRelease-1, ButtonRelease-2, ButtonRelease-3,
Double-Button-1, Double-Button-2, Double-Button-3,
Enter, Leave etc

4-Event-Related Methods:Each widget w supplies the


following event-related methods.
bind
• w.bind(event_name,callable[,'+'])
• w.bind(event_name,callable) sets callable as the
callback for event_name on w.
• w.bind(event_name,callable,'+') adds callable to the
previous bindings for event_name on w.
Harendra Sharma (Assistanat Professor)
bind_all
w.bind_all(event_name,callable[,'+'])
w.bind_all(event_name,callable) sets callable as the callback
for event_name on any widget of the application, whatever
widget w you call the method on.
w.bind_all(event_name,callable,'+') adds callable to the
previous bindings for event_name on any widget.

unbind
w.unbind(event_name)
Removes all callbacks for event_name on w.

unbind_all
w.unbind_all(event_name)
Removes all callbacks for event_name on any widget,
previously set by calling method bind_all on any widget.
Harendra Sharma (Assistanat Professor)
Example: Handling Mouse event
from tkinter import *
var = Tk()
def leftclick(event):
print("left")
def middleclick(event):
print("middle")
def rightclick(event):
print("right")
frame = Frame(var, width=300, height=250)
frame.bind("<Button-1>", leftclick)
frame.bind("<Button-2>", middleclick)
frame.bind("<Button-3>", rightclick)
frame.pack()
var.mainloop()
Harendra Sharma (Assistanat Professor)
Example : Capturing keyboard events
from tkinter import *
root = Tk()
def key(event):
print("pressed", repr(event.char))
def callback(event):
frame.focus_set()
print("clicked at", event.x, event.y)
frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()
Harendra Sharma (Assistanat Professor)
Harendra Sharma (Assistanat Professor)

You might also like