0% found this document useful (0 votes)
19 views

Updated - Project 2 - GUI

The document discusses creating graphical user interfaces (GUIs) in Python using the tkinter library. It introduces tkinter, describes how to import tkinter and create basic GUI screens by setting window properties and adding widgets like labels, entries, and buttons.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Updated - Project 2 - GUI

The document discusses creating graphical user interfaces (GUIs) in Python using the tkinter library. It introduces tkinter, describes how to import tkinter and create basic GUI screens by setting window properties and adding widgets like labels, entries, and buttons.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Project 2

Graphical User Interface (GUI)

Objectives

1. Introduce GUI
2. Describe how to install tkinter
3. Explore the GUI tkinter library
- 209 -

1.1 Introduction

graphical user interface (GUI), a computer program that


enables a person to communicate with a computer through the
use of symbols, visual metaphors, and pointing devices. Best
known for its implementation in Apple Inc.’s Macintosh
and Microsoft Corporation’s Windows operating system, the
GUI has replaced the arcane and difficult textual interfaces of
earlier computing with a relatively intuitive system that has
made computer operation not only easier to learn but more
pleasant and natural. The GUI is now the standard computer
interface and its components have themselves become
unmistakable cultural artifacts.

A graphics-based operating system interface that uses icons,


menus, and a mouse (to click on the icon or pull down the
menus) to manage interaction with the system. Developed by
Xerox, the GUI was popularized by the Apple Macintosh in the
1980s.

Python provides various options for developing graphical user


interfaces (GUIs). Most important are listed below.

Project 2: Graphical User Interface (GUI)


- 210 -

• Tkinter − Tkinter is the Python interface to the Tk


GUI toolkit shipped with Python. We would look this
option in this chapter.
• wxPython − This is an open-source Python interface
for wxWindows http://wxpython.org.
• JPython − JPython is a Python port for Java which
gives Python scripts seamless access to Java class
libraries on the local machine http://www.jython.org

Python offers multiple options for developing GUI (Graphical


User Interface). Out of all the GUI methods, tkinter is the most
used method. It is a standard Python interface to the Tk GUI
toolkit shipped with Python. Python with tkinter is the fastest
and easiest way to create the GUI applications. Creating a GUI
using tkinter is an easy task.

1.2 Importing tkinter

Tkinter is the standard GUI library for Python. Python when


combined with Tkinter provides a fast and easy way to create
GUI applications. Tkinter provides a powerful object-oriented
interface to the Tk GUI toolkit.

Creating a GUI application using Tkinter is an easy task. All


you need to do is perform the following steps −
Project 2: Graphical User Interface (GUI)
- 211 -

• Import the Tkinter module.

• Create the GUI application main window.

• Add one or more of the above-mentioned widgets to the


GUI application.

• Enter the main event loop to act against each event


triggered by the user.

Importing tkinter is same as importing any other module in the


Python code.

Note that the name of the module in Python 2.x is ‘Tkinter’


and in Python 3.x it is ‘tkinter’.

import tkinter

The tkinter package (“Tk interface”) is the standard Python


interface to the Tcl/Tk GUI toolkit. Both Tk and tkinter are
available on most Unix platforms, including macOS, as well as
on Windows systems.

Running python -m tkinter from the command line should open


a window demonstrating a simple Tk interface, letting you know
that tkinter is properly installed on your system, and also

Project 2: Graphical User Interface (GUI)


- 212 -

showing what version of Tcl/Tk is installed, so you can read the


Tcl/Tk documentation specific to that version.

Tkinter supports a range of Tcl/Tk versions, built either with or


without thread support. The official Python binary release
bundles Tcl/Tk 8.6 threaded. See the source code for
the _tkinter module for more information about supported
versions.

1.3 Creating GUI Screen

First basic screen

GUI elements and their functionality are defined in the Tkinter


module. The following code demonstrates the steps in creating
a UI.

from tkinter import *


window=Tk()
# add widgets here
window.title('Hello Python')
window.geometry("300x200")
window.mainloop()

Project 2: Graphical User Interface (GUI)


- 213 -

First, import the TKinter module. After importing, setup the


application object by calling the Tk () function. This will create
a top-level window (root) having a frame with a title bar, control
box with the minimize and close buttons, and a client area to
hold other widgets.

The title in tkinter refers to a name assigned to the application


window. It is mostly found on the top of the application. For
this, we can use the title() function.

We create a widget object using the Tk() function and use


the title() function to add a title to this window.

The geometry() method defines the width, height and


coordinates of the top left corner of the frame as below (all
values are in pixels): window.geometry ("widthxheight)

The application object then enters an event listening loop by


calling the mainloop() method. The window won't appear until
we enter the Tkinter event loop: window.mainloop()

The application is now constantly waiting for any event


generated on the elements in it. The event could be text entered
in a text field, a selection made from the dropdown or radio
button, single/double click actions of mouse, etc.

Project 2: Graphical User Interface (GUI)


- 214 -

The application's functionality involves executing appropriate


call back functions in response to a particular type of event. The
above code will create the following window:

Change the window position

When you run the previous application, you’ll observe that the
position of the window located at the top left side of the screen.

Project 2: Graphical User Interface (GUI)


- 215 -

So, we can use the XPOS+YPOS to change the window


position.

window.geometry ("widthxheight+ XPOS+YPOS")

from tkinter import *


window=Tk()
# add widgets here
window.title('Hello Python')
window.geometry("300x200+400+300")
window.mainloop()

Now the Tkinter window is appearing at a different position


(400 shifted on X-axis and 300 shifted on Y-axis).

Project 2: Graphical User Interface (GUI)


- 216 -

Change the window size

You can set the size of Tkinter window by calling geometry()


function on the window with width and height string passed as
argument.

we will use geometry() method to set a fixed window size of 600 by


200 to the Tk() window.

from tkinter import *


window=Tk()
# add widgets here
window.title('Hello Python')
window.geometry("600x200+400+300")
window.mainloop()

Project 2: Graphical User Interface (GUI)


- 217 -

1.4 GUI components

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.To use a label, you just have to specify what to display in
it (this can be text, a bitmap, or an image). Syntax:

w = Label ( master, option, … )

from tkinter import *


window=Tk()
# add widgets here

Project 2: Graphical User Interface (GUI)


- 218 -

window.title('Hello Python')
window.geometry("400x300")
L= Label(window, text="Username")
L.pack()
window.mainloop()

The first parameter of the Label call is the name of the parent
window, in our case "window". So, our Label widget is a child
of the window widget. The keyword parameter "text" specifies
the text to be shown. The pack() method tells Tk to fit the size
of the window to the given text. Our script will remain in the
event loop until we close the window.

Project 2: Graphical User Interface (GUI)


- 219 -

Parameters:
• master: This represents the parent window

• options: Below is the list of most used options for this


widget. You can find them in the following documentation
link:
https://docs.python.org/3/library/tkinter.ttk.html#label-
options
Add border and background

from tkinter import *


window=Tk()
# add widgets here
window.title('Hello Python')
window.geometry("400x300")
L= Label(window,
text="Username",bg='red',bd=20)
L.pack()
window.mainloop()

Project 2: Graphical User Interface (GUI)


- 220 -

Add image
from tkinter import *
window=Tk()
# add widgets here
window.title('Hello Python')
window.geometry("400x300")
logo = PhotoImage(file="bis.png")
L1= Label(window, text="Username",
image=logo)
L1.pack()
L2= Label(window, text="Business
Information Systems")
L2.pack()

Project 2: Graphical User Interface (GUI)


- 221 -

Entry

The Entry widget is used to accept single-line text strings from


a user.

• If you want to display multiple lines of text that can be


edited, then you should use the Text widget.

• If you want to display one or more lines of text that


cannot be modified by the user, then you should use
the Label widget.

Syntax

Here is the simple syntax to create this widget −

w = Entry( master, option, ... )

Parameters

• master − This represents the parent window.

• options − Here is the list of most used options for this


widget:
https://www.tutorialspoint.com/python/tk_entry.htm

Project 2: Graphical User Interface (GUI)


- 222 -

Example:

from tkinter import *


window=Tk()
# add widgets here
window.title('Hello Python')
window.geometry("400x300")
L1= Label(window, text="Username")
L1.pack(side = LEFT)
E1 = Entry(window, bd =7)
E1.pack(side = RIGHT)
window.mainloop()

Button

The Button widget is used to add buttons in a Python


application. These buttons can display text or images that
convey the purpose of the buttons. You can attach a function
or a method to a button which is called automatically when you
click the button.

Project 2: Graphical User Interface (GUI)


- 223 -

Syntax

Here is the simple syntax to create this widget −

w = Button (master, option=value, ... )

Example

from tkinter import *


top = Tk()
L1 = Label(top, text="User Name")
L1.pack()
E1 = Entry(top, bd =5)
E1.pack()
B1=Button(top,text="Submit")
B1.pack()
top.mainloop()

output

Project 2: Graphical User Interface (GUI)


- 224 -

Using side inside pack() method to locate GUI components

Example

from tkinter import *

top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
B1=Button(top,text="Submit")
B1.pack(side = BOTTOM)
top.mainloop()

Project 2: Graphical User Interface (GUI)


- 225 -

Frame

The Frame widget is very important for the process of grouping


and organizing other widgets in a somehow friendly way. It
works like a container, which is responsible for arranging the
position of other widgets.

It uses rectangular areas in the screen to organize the layout and


to provide padding of these widgets. A frame can also be used
as a foundation class to implement complex widgets.

Syntax

Here is the simple syntax to create this widget −

w = Frame ( master, option, ... )

Using side inside Frame class to locate GUI components


inside frames.

Example

from tkinter import *


top = Tk()
frame1 = Frame(top)
frame1.pack(side = LEFT)
frame2 = Frame(top)
frame2.pack( side = RIGHT )

Project 2: Graphical User Interface (GUI)


- 226 -

frame3 = Frame(top)
frame3.pack( side = BOTTOM )
L1 = Label(frame1, text="User Name")
L1.pack()
E1 = Entry(frame2, bd =5)
E1.pack()
L2 = Label(frame1, text="Password")
L2.pack()
E2 = Entry(frame2, bd =5)
E2.pack()
B1=Button(frame3,text="Submit")
B1.pack()
top.mainloop()

Check Button

The Checkbutton widget is used to display several options to a


user as toggle buttons. The user can then select one or more
options by clicking the button corresponding to each option.

You can also display images in place of text.

Project 2: Graphical User Interface (GUI)


- 227 -

Syntax

Here is the simple syntax to create this widget −

w = Checkbutton ( master, option, ... )

Radio button

This widget implements a multiple-choice button, which is a


way to offer many possible selections to the user and lets user
choose only one of them.

To implement this functionality, each group of radiobuttons


must be associated to the same variable and each one of the
buttons must symbolize a single value. You can use the Tab
key to switch from one radionbutton to another.

Syntax

Here is the simple syntax to create this widget −

w = Radiobutton ( master, option, ... )

Project 2: Graphical User Interface (GUI)


- 228 -

Example

from tkinter import *


s = Tk()
s.title('Hello GUI')
s.geometry('400x300')
L1 = Label(s, text="Username")
L1.pack()
E1 = Entry(s)
E1.pack()
R1 = Radiobutton(s, text="Male",value=1)
R1.pack()
R2 = Radiobutton(s, text="FeMale",value=2)
R2.pack()
C1 = Checkbutton(s, text="Red")
C1.pack()
C2 = Checkbutton(s, text="Blue")
C2.pack()
B1=Button(s,text="Submit")
B1.pack()
s.mainloop()

Project 2: Graphical User Interface (GUI)


- 229 -

Designing of Simple Calculator using many Frames


from tkinter import *
top = Tk()
top.title(string='Simple Calculator')
top.geometry('400x300')

frame1 = Frame(top)
frame1.pack(side = LEFT)
frame2 = Frame(top)
frame2.pack( side = RIGHT )
frame3 = Frame(top)
frame3.pack( side = BOTTOM )
frame4 = Frame(top)
frame4.pack( side = BOTTOM )
L1 = Label(frame1, text="First Number")
L1.pack()
E1 = Entry(frame2, bd =5)
E1.pack()
L2 = Label(frame1, text="Second Number")
L2.pack()
E2 = Entry(frame2, bd =5)
E2.pack()
L3 = Label(frame1, text="Result")
L3.pack()
E3 = Entry(frame2, bd =5)
E3.pack()
B1=Button(frame4,text="+")
B1.pack(side = LEFT)
B2=Button(frame4,text="-")
B2.pack(side = LEFT)
B3=Button(frame4,text="/")
B3.pack(side = RIGHT)
B4=Button(frame4,text="*")
B4.pack(side = RIGHT)

Project 2: Graphical User Interface (GUI)


- 230 -

B5=Button(frame3,text="Exit")
B5.pack(side = LEFT)
B6=Button(frame3,text="Clear")
B6.pack(side = RIGHT)
top.mainloop()

1.5 Message boxes

Python Tkinter – MessageBox Widget is used to display the


message boxes in the python applications. This module is used
to display a message using provides several functions.

Syntax:

messagebox.Function_Name(title, message [, options])

Project 2: Graphical User Interface (GUI)


- 231 -

Parameters:
There are various parameters:
• Function_Name: This parameter is used to represents an
appropriate message box function.
• title: This parameter is a string which is shown as a title of
a message box.
• message: This parameter is the string to be displayed as a
message on the message box.
• options: There are two options that can be used are:
1. default: This option is used to specify the default
button like ABORT, RETRY, or IGNORE in the
message box.
2. parent: This option is used to specify the window on
top of which the message box is to be displayed.
Function_Name:
There are functions or methods available in the messagebox
widget.
1. showinfo(): Show some relevant information to the
user.
2. showwarning(): Display the warning to the user.
3. showerror(): Display the error message to the user.
4. askquestion(): Ask question and user has to answered
in yes or no.

Project 2: Graphical User Interface (GUI)


- 232 -

5. askokcancel(): Confirm the user’s action regarding


some application activity.
6. askyesno(): User can answer is yes or no for some
action.
7. askretrycancel(): Ask the user about doing a particular
task again or not.
Example:
from tkinter import *
from tkinter import messagebox

root = Tk()
root.geometry("300x200")
w = Label(root, text='Test massagebox',
font="50")
w.pack()
messagebox.showinfo("showinfo",
"Information")
messagebox.showwarning("showwarning",
"Warning")
messagebox.showerror("showerror", "Error")
messagebox.askquestion("askquestion", "Are
you sure?")
messagebox.askokcancel("askokcancel",
"Want to continue?")
messagebox.askyesno("askyesno", "Find the
value?")
messagebox.askretrycancel("askretrycancel"
, "Try again?")
root.mainloop()

Project 2: Graphical User Interface (GUI)


- 233 -

Output

Project 2: Graphical User Interface (GUI)


- 234 -

Project 2: Graphical User Interface (GUI)


- 235 -

1.6 Event handling

An Event Handler is a class, part of events, which simply is


responsible for managing all callbacks which are to be executed
when invoked. An Event is simply an action, like clicking a
button, which then leads to another event, which the developer
already assigns. The core of Python Event Handler is to manage
these events and organize and make them work as intended in
an intended manner. It is a known fact that programs that follow
proper event handling are flexible and easy to manage.
Debugging such programs is easy. Another advantage is the
ability to change the program at any given point, according to
needs.

One of the examples for python is the Python Interface of


Tkinter. Tkinter is a GUI tool for python, which is always

Project 2: Graphical User Interface (GUI)


- 236 -

waiting for an event to happen. It provides an easy mechanism


for a developer to efficiently manage the events. To manage the
link between the event of click and the next action’s event is the
core process of an event handler in python.

Button click event

Sometimes, handling events in a Tkinter application can become


a daunting task for us. We must manage the action and events
which need to be executed at the time of running the application.
The Button widget is useful for handling such events. We can
use Button widget to perform a certain task or event by passing
the callback in the command.

While giving the command to the Button widget, we can have


an optional lambda or anonymous functions which interpret to
ignore any errors in the program. These are just like a general
function, but they don't have any function bodies in it.

Example

In this example, we will create a button and pass the function to


show a popup message on the window.

from tkinter import *


from tkinter.messagebox import showinfo
win= Tk()

Project 2: Graphical User Interface (GUI)


- 237 -

win.geometry("700x350")
def show_msg():
showinfo("Message","Hey There! I hope
you are doing well.")
Label(win, text= "Welcome BIS!", font=
('Aerial 17 bold italic')).pack(pady= 30)
Button(win, text= "Click Here",
command=show_msg).pack(pady= 20)
win.mainloop()

Output

Running the above code will display a window with a Button


widget. When we click the button, it will trigger an event to
happen. Now, click the Button to see the event of displaying the
popup message on the screen.

Project 2: Graphical User Interface (GUI)


- 238 -

Example:

from tkinter import *


from tkinter.messagebox import showinfo
ws = Tk()
ws.title(string='')
ws.geometry('400x300')
frame = LabelFrame(ws, text='Hello_World',
bg='#f0f0f0', font=(30))
frame.pack(expand=True, fill=BOTH)
Button(frame, text='Submit',
command=lambda: showinfo("showinfo",
"Welcome to your first App")).pack()
ws.mainloop()

Project 2: Graphical User Interface (GUI)


- 239 -

Navigating Multiple screens Example

We are learning about how multiple windows work. By


Multiple Windows, we mean connecting one page with other
pages that are interlinked with each other and open in a new tab
or even redirect us to a new page.

import tkinter as tk
def New_Window():
window = tk.Tk()
window.title("Python Main Window")
window.geometry('400x300')
L = tk.Label(window, text="Welcome to
Python Second window")
L.pack()
ws = tk.Tk()
ws.title("Python Second Window")
ws.geometry('400x300')
L1 = tk.Label(ws, text="Welcome to Python
Main Window")
L1.pack()
button = tk.Button(ws, text="Click ME",
bg='White', fg='Black', command=lambda:

Project 2: Graphical User Interface (GUI)


- 240 -

New_Window())
button.pack()
ws.mainloop()

Project 2: Graphical User Interface (GUI)


- 241 -

GUI Programs Using Button Click event


Program 1: Press A Button

from tkinter import *

top = Tk()
top.title(string='Press A Button')
top.geometry('400x300')

def java():
output_label.config(text='You Pressed
Java Button')
def python():
output_label.config(text='You Pressed
Python Button')

B1=Button(top,text="Java", command=java)
B1.pack()
B2=Button(top,text="Python",
command=python)
B2.pack()
output_label = Label(top)
output_label.pack()
top.mainloop()

Project 2: Graphical User Interface (GUI)


- 242 -

Program 2: User Information

from tkinter import *

top = Tk()
top.title(string='User Information')
top.geometry('400x500')
def user():
name=E1.get()
password=E2.get()
email=E3.get()
output_text="You Registered Successfully
\n Name: "+name+"\n Password:
"+password+"\n Email: "+email
output_label.config(text=output_text)
logo = PhotoImage(file="bis.png")
L= Label(top, text="Username", image=logo)
L.pack()
L1 = Label(top, text="Enter your Name")
L1.pack()
E1 = Entry()
E1.pack()
L2 = Label(top, text="Enter your Password")
L2.pack()
E2 = Entry()
E2.pack()
L3 = Label(top, text="Enter your E-mail")
L3.pack()
E3 = Entry()
E3.pack()
B1=Button(top,text="Submit", command=user)
B1.pack()

output_label = Label(top)
output_label.pack()
top.mainloop()

Project 2: Graphical User Interface (GUI)


- 243 -

Project 2: Graphical User Interface (GUI)


- 244 -

Project 2: Graphical User Interface (GUI)


- 245 -

Program 3: Compute BMI

BMI= weight/(height*height)

from tkinter import *

top = Tk()
top.title(string='Compute BMI')
top.geometry('400x300')

def bmi():
w=float(E1.get())
h =float(E2.get())
bmi=w/(h*h)
if bmi<16:
output_text="You are seriously
Underweight"
elif bmi<18:
output_text="You are Underweight"
elif bmi < 24:
output_text = "You are Normal
weight"
elif bmi < 29:

Project 2: Graphical User Interface (GUI)


- 246 -

output_text = "You are Overweight"


elif bmi < 35:
output_text = "You are seriously
Overweight"
else:
output_text = "You are Gravely
Overweight"
output_label.config(text=output_text)

def clear():
E1.delete(0,'end')
E2.delete(0,'end')
output_label.config(text='')

L1 = Label(top, text="Enter your Weight in


Kilograms")
L1.pack()
E1 = Entry()
E1.pack()
L2 = Label(top, text="Enter your Height in
Meters")
L2.pack()
E2 = Entry()
E2.pack()
B1=Button(top,text="Compute BMI",
command=bmi)
B1.pack()
B2=Button(top,text="Clear", command=clear)
B2.pack()
output_label = Label(top)
output_label.pack()
top.mainloop()

Project 2: Graphical User Interface (GUI)


- 247 -

Project 2: Graphical User Interface (GUI)


- 248 -

Program 4: Guess a Number

from tkinter import *


import random as r

top = Tk()
top.title(string='Guess A Number')
top.geometry('400x300')
random = r.randint(0, 100)
def guess():
num=int(E1.get())
if num>100 or num<0:
output_text="Your number should be
between 0 to 100"
elif num==random:
output_text="Congratulations You
are Won"
elif num<random:
output_text = "Your number is less
than random number"
else:
output_text = "Your number is
greater than random number"
output_label.config(text=output_text)
def clear():
E1.delete(0,'end')
output_label.config(text='')

L1 = Label(top, text="Enter integer Number


(between 0 to 100)")
L1.pack()
E1 = Entry()
E1.pack()
B1=Button(top,text="Guess", command=guess)
B1.pack()

Project 2: Graphical User Interface (GUI)


- 249 -

B2=Button(top,text="Clear", command=clear)
B2.pack()
output_label = Label(top)
output_label.pack()
top.mainloop()

Project 2: Graphical User Interface (GUI)


- 250 -

Program 5: Add two numbers

from tkinter import *

top = Tk()
top.title(string='Add Numbers')
top.geometry('400x300')

def add():
f=float(E1.get())
s=float(E2.get())
r=f+s
output_text = "The result of Addition is
"+str(r)
output_label.config(text=output_text)

def clear():
E1.delete(0,'end')
E2.delete(0,'end')
output_label.config(text='')

L1 = Label(top, text="Enter the first


number")
L1.pack()
E1 = Entry()
E1.pack()
L2 = Label(top, text="Enter the second
number")
L2.pack()
E2 = Entry()
E2.pack()
B1=Button(top,text="Add", command=add)
B1.pack()

B3=Button(top,text="Clear", command=clear)
B3.pack()

Project 2: Graphical User Interface (GUI)


- 251 -

output_label = Label(top)
output_label.pack()
top.mainloop()

Project 2: Graphical User Interface (GUI)


- 252 -

Program 6: Simple Calculator (using Frame to organize


widgets)

from tkinter import *

top = Tk()
top.title(string='Simple Calculator')
top.geometry('400x300')

def add():
result=int(E1.get())+int(E2.get())
E3.insert(0,result)
def sub():
result=int(E1.get())-int(E2.get())
E3.insert(0,result)

def div():
result=int(E1.get())/int(E2.get())
E3.insert(0,result)
def mlt():
result=int(E1.get())*int(E2.get())
E3.insert(0,result)
def exit():
top.quit()
def clear():
E1.delete(0, 'end')
E2.delete(0, 'end')
E3.delete(0, 'end')
frame1 = Frame(top)
frame1.pack(side = LEFT)
frame2 = Frame(top)
frame2.pack( side = RIGHT )
frame3 = Frame(top)
frame3.pack( side = BOTTOM )
frame4 = Frame(top)
frame4.pack( side = BOTTOM )

Project 2: Graphical User Interface (GUI)


- 253 -

L1 = Label(frame1, text="First Number")


L1.pack()
E1 = Entry(frame2, bd =5)
E1.pack()
L2 = Label(frame1, text="Second Number")
L2.pack()
E2 = Entry(frame2, bd =5)
E2.pack()
L3 = Label(frame1, text="Result")
L3.pack()
E3 = Entry(frame2, bd =5)
E3.pack()
B1=Button(frame4,text="+",command=add)
B1.pack(side = LEFT)
B2=Button(frame4,text="-",command=sub)
B2.pack(side = LEFT)
B3=Button(frame4,text="/",command=div)
B3.pack(side = RIGHT)
B4=Button(frame4,text="*",command=mlt)
B4.pack(side = RIGHT)
B5=Button(frame3,text="Exit",command=exit)
B5.pack(side = LEFT)
B6=Button(frame3,text="Clear",command=clear
)
B6.pack(side = RIGHT)
top.mainloop()

Project 2: Graphical User Interface (GUI)


- 254 -

Project 2: Graphical User Interface (GUI)


- 255 -

1.7 Menus

The tkinter menu is a top-level pulldown menu. They are shown


just under the title bar, as you’d expect from traditional gui apps.

The menu can have multiple sub menus and each sub menu can
contain items. Menu items can be associated with callback
methods, meaning when you click them a Python method is
called.

tkinter menu example

The menu example below adds a menu to a basic tkinter


window. It has one clickable menu item but shows a complete
menu.

import tkinter as tk
from tkinter import Menu
from tkinter import Frame
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master

menu = Menu(self.master)
self.master.config(menu=menu)

fileMenu = Menu(menu)

Project 2: Graphical User Interface (GUI)


- 256 -

fileMenu.add_command(label="Item")

fileMenu.add_command(label="Exit",
command=self.exitProgram)
menu.add_cascade(label="File",
menu=fileMenu)

editMenu = Menu(menu)

editMenu.add_command(label="Undo")

editMenu.add_command(label="Redo")
menu.add_cascade(label="Edit",
menu=editMenu)

def exitProgram(self):
exit()

root = root = tk.Tk()


app = Window(root)
root.wm_title("Tkinter window")
root.mainloop()

Project 2: Graphical User Interface (GUI)


- 257 -

Project 2: Graphical User Interface (GUI)


- 258 -

Creating simple menu

First, create a root window and set its title to 'Menu Demo':

root = tk.Tk()
root.title('Menu Demo')

Second, create a menu bar and assign it to the menu option of


the root window:

menubar = Menu(root)
root.config(menu=menubar)

Note that each top-level window can only have only one menu
bar.

Third, create a File menu whose container is the menubar:

file_menu = Menu(menubar)

Fourth, add a menu item to the file_menu:

file_menu.add_command(
label='Exit',
command=root.destroy,
)

Project 2: Graphical User Interface (GUI)


- 259 -

In this example, the label of the menu item is Exit.

When you click the Exit menu item, Python will call
the root.destroy() method automatically to close
the root window.

Finally, add the File menu to the menubar:

menubar.add_cascade(
label="File",
menu=file_menu,
underline=0
)

The underline option allows you to create a keyboard shortcut.


It specifies the character position that should be underlined.

Note that the position starts from zero. In this example, we


specify it as the first character which is F. And you can select it
by using the Alt+F keyboard shortcut.

Put it all together:

import tkinter as tk
from tkinter import Menu

# root window

Project 2: Graphical User Interface (GUI)


- 260 -

root = tk.Tk()
root.title('Menu Demo')

# create a menubar
menubar = Menu(root)
root.config(menu=menubar)

# create a menu
file_menu = Menu(menubar)

# add a menu item to the menu


file_menu.add_command(
label='Exit',
command=root.destroy
)

# add the File menu to the menubar


menubar.add_cascade(
label="File",
menu=file_menu
)

root.mainloop()

Output:

Project 2: Graphical User Interface (GUI)


- 261 -

Project 2: Graphical User Interface (GUI)


- 262 -

1.8 Calculator Application

Below is what the GUI looks like:

Let’s create a GUI based simple calculator using the Python


Tkinter module, which can perform basic arithmetic operations
addition, subtraction, multiplication, and division.

Project 2: Graphical User Interface (GUI)


- 263 -

Below is the implementation:


# calculator using Tkinter

# import everything from tkinter module


from tkinter import *

# globally declare the expression


variable
expression = ""

# Function to update expression


# in the text entry box
def press(num):
# point out the global expression
variable
global expression

# concatenation of string
expression = expression + str(num)

# update the expression by using


set method
equation.set(expression)

# Function to evaluate the final


expression
def equalpress():
# Try and except statement is used
# for handling the errors like zero
# division error etc.

Project 2: Graphical User Interface (GUI)


- 264 -

# Put that code inside the try


block
# which may generate the error
try:

global expression

# eval function evaluate the


expression
# and str function convert the
result
# into string
total = str(eval(expression))

equation.set(total)

# initialize the expression


variable
# by empty string
expression = ""

# if error is generate then handle


# by the except block
except:

equation.set(" error ")


expression = ""

# Function to clear the contents


# of text entry box

Project 2: Graphical User Interface (GUI)


- 265 -

def clear():
global expression
expression = ""
equation.set("")

# Driver code
if __name__ == "__main__":
# create a GUI window
gui = Tk()

# set the background colour of GUI


window
gui.configure(background="light
green")

# set the title of GUI window


gui.title("Simple Calculator")

# set the configuration of GUI


window
gui.geometry("270x150")

# StringVar() is the variable class


# we create an instance of this
class
equation = StringVar()

# create the text entry box for


# showing the expression .
expression_field = Entry(gui,
textvariable=equation)

Project 2: Graphical User Interface (GUI)


- 266 -

# grid method is used for placing


# the widgets at respective
positions
# in table like structure .
expression_field.grid(columnspan=4,
ipadx=70)

# create a Buttons and place at a


particular
# location inside the root window .
# when user press the button, the
command or
# function affiliated to that
button is executed .
button1 = Button(gui, text=' 1 ',
fg='black', bg='red',
command=lambda:
press(1), height=1, width=7)
button1.grid(row=2, column=0)

button2 = Button(gui, text=' 2 ',


fg='black', bg='red',
command=lambda:
press(2), height=1, width=7)
button2.grid(row=2, column=1)

button3 = Button(gui, text=' 3 ',


fg='black', bg='red',
command=lambda:
press(3), height=1, width=7)
button3.grid(row=2, column=2)

Project 2: Graphical User Interface (GUI)


- 267 -

button4 = Button(gui, text=' 4 ',


fg='black', bg='red',
command=lambda:
press(4), height=1, width=7)
button4.grid(row=3, column=0)

button5 = Button(gui, text=' 5 ',


fg='black', bg='red',
command=lambda:
press(5), height=1, width=7)
button5.grid(row=3, column=1)

button6 = Button(gui, text=' 6 ',


fg='black', bg='red',
command=lambda:
press(6), height=1, width=7)
button6.grid(row=3, column=2)

button7 = Button(gui, text=' 7 ',


fg='black', bg='red',
command=lambda:
press(7), height=1, width=7)
button7.grid(row=4, column=0)

button8 = Button(gui, text=' 8 ',


fg='black', bg='red',
command=lambda:
press(8), height=1, width=7)
button8.grid(row=4, column=1)

button9 = Button(gui, text=' 9 ',

Project 2: Graphical User Interface (GUI)


- 268 -

fg='black', bg='red',
command=lambda:
press(9), height=1, width=7)
button9.grid(row=4, column=2)

button0 = Button(gui, text=' 0 ',


fg='black', bg='red',
command=lambda:
press(0), height=1, width=7)
button0.grid(row=5, column=0)

plus = Button(gui, text=' + ',


fg='black', bg='red',
command=lambda:
press("+"), height=1, width=7)
plus.grid(row=2, column=3)

minus = Button(gui, text=' - ',


fg='black', bg='red',
command=lambda:
press("-"), height=1, width=7)
minus.grid(row=3, column=3)

multiply = Button(gui, text=' * ',


fg='black', bg='red',
command=lambda:
press("*"), height=1, width=7)
multiply.grid(row=4, column=3)

divide = Button(gui, text=' / ',


fg='black', bg='red',
command=lambda:

Project 2: Graphical User Interface (GUI)


- 269 -

press("/"), height=1, width=7)


divide.grid(row=5, column=3)

equal = Button(gui, text=' = ',


fg='black', bg='red',
command=equalpress,
height=1, width=7)
equal.grid(row=5, column=2)

clear = Button(gui, text='Clear',


fg='black', bg='red',
command=clear,
height=1, width=7)
clear.grid(row=5, column='1')

Decimal = Button(gui, text='.',


fg='black', bg='red',
command=lambda:
press('.'), height=1, width=7)
Decimal.grid(row=6, column=0)
# start the GUI
gui.mainloop()

Project 2: Graphical User Interface (GUI)


- 270 -

Chapter Summary

Tkinter is lightweight and relatively painless to use compared to other


frameworks. This makes it a compelling choice for building GUI
applications in Python, especially for applications where a modern sheen
is unnecessary, and the top priority is to build something that’s functional
and cross-platform quickly.
• In this chapter, you learned how to:
• Get started with Tkinter with a “Hello, World!” application
• Work with widgets, such as buttons and text boxes
• Control your application layout with geometry managers
• Make your applications interactive by associating button clicks to
Python functions

Project 2: Graphical User Interface (GUI)


- 271 -

Notes

----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------

Project 2: Graphical User Interface (GUI)


- 272 -

Notes

----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------

Project 2: Graphical User Interface (GUI)

You might also like