Tkinter
Tkinter
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.
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
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.
Note: This gets displayed in the window. A Label widget can display
either text or an icon or other image.
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:
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.
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.
Syntax:
photo = PhotoImage(file = "path_of_file")
path_of_file is any valid path available on your local
machine.
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:
Syntax:
button = Radiobutton(master, text=”Name on Button”, variable =
“shared variable”, value = “values of each button”, options =
values, …)
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.
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.
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.
Syntax:
combobox = ttk.Combobox(master, option=value, ...)
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.
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
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)