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

Unit 5

The document discusses different GUI methods in Python with a focus on tkinter. Tkinter is introduced as the most commonly used method for building GUIs in Python. The key steps for creating a tkinter app are described as importing tkinter, creating a main window, adding widgets, and triggering events on the widgets. Widget classes and geometry managers available in tkinter are also outlined.

Uploaded by

susan babu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit 5

The document discusses different GUI methods in Python with a focus on tkinter. Tkinter is introduced as the most commonly used method for building GUIs in Python. The key steps for creating a tkinter app are described as importing tkinter, creating a main window, adding widgets, and triggering events on the widgets. Widget classes and geometry managers available in tkinter are also outlined.

Uploaded by

susan babu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT-5

Python offers multiple options for developing GUI (Graphical User Interface). Out of all
the GUI methods, tkinter is the most commonly used method. It is a standard Python
interface to the Tk GUI toolkit shipped with Python. Python tkinter is the fastest and
easiest way to create GUI applications. Creating a GUI using tkinter is an easy task.
To create a tkinter Python app:
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.
Importing a tkinter is the same as importing any other module in the code. Note that
the name of the module in Python 2.x is ‘Tkinter’ and in Python 3.x it is ‘tkinter’.

import tkinter
There are two main methods used which the user needs to remember while creating
the Python application with GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To
create a main window, tkinter offers a method
‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change
the name of the window, you can change the className to the desired one. The
basic code used to create the main window of the application is:
m=tkinter.Tk() where m is the name of the main window object

2. mainloop(): There is a method known by the name mainloop() is used when your
application is ready to run. mainloop() is an infinite loop used to run the
application, wait for an event to occur and process the event as long as the window
is not closed.
m.mainloop()

import tkinter

m = tkinter.Tk()

#widgets are added here

m.mainloop()

GEOMETRY MANAGER CLASSES


Tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainly three geometry
manager classes class.
1. pack() method:It organizes the widgets in blocks before placing in the parent
widget.
2. grid() method:It organizes the widgets in grid (table-like structure) before
placing in the parent widget.
3. place() method:It organizes the widgets by placing them on specific positions
directed by the programmer.

Top Level Windows

What is a Widget According to the Free On-Line Dictionary of Computing, the definition
of a widget is: widget: [possibly evoking ”window gadget”] In graphical user interfaces, a
combination of a graphic symbol and some program code to perform a specific function.
E.g. a scroll-bar or button. Windowing systems usually provide widget libraries
containing commonly used widgets drawn in a certain style and with consistent
behaviour. A widget is therefore a graphical object that is available from the Tkinter
library. It is a kind of graphical building block. Intuitively, widgets are implemented as
classes in Tkinter. Each widget therefore has a constructor, a destructor, its own set of
properties and methods, and so on. While most other GUI toolkits have a very complex
widget hierarchy, Tkinter’s hierarchy is extremely simple. All widgets (like Button,
Checkbutton, etc.) are dereived from the Widget class. All widget subclasses occupy the
same level in the hierachy tree.

The Different Widgets 3.2.1 Toplevel The Toplevel is technically not a widget, although
this is more or less transparent to the user.

The Toplevel widget is used to create and display the toplevel windows which are directly
managed by the window manager. The toplevel widget may or may not have the parent
window on the top of them.

The toplevel widget is used when a python application needs to represent some extra
information, pop-up, or the group of widgets on the new window.

The toplevel windows have the title bars, borders, and other window decorations.

The syntax to use the Toplevel widget is given below.

Syntax

1. w = Toplevel(options)
A List of possible options is given below.

SN Options Description

1 bg It represents the background color of the window.

2 bd It represents the border size of the window.

3 cursor The mouse pointer is changed to the cursor type set to the arrow, dot,
etc. when the mouse is in the window.

4 class_ The text selected in the text widget is exported to be selected to the
window manager. We can set this to 0 to make this behavior false.

5 font The font type of the text inserted into the widget.

6 fg The foreground color of the widget.

7 height It represents the height of the window.

8 relief It represents the type of the window.

9 width It represents the width of the window,

Methods

The methods associated with the Toplevel widget is given in the following list.

SN Method Description

1 deiconify() This method is used to display the window.

2 frame() It is used to show a system dependent window


identifier.

3 group(window) It is used to add this window to the specified window


group.

4 iconify() It is used to convert the toplevel window into an icon.

5 protocol(name, It is used to mention a function which will be called


function) for the specific protocol.
6 state() It is used to get the current state of the window.
Possible values are normal, iconic, withdrawn, and
icon.

7 transient([master]) It is used to convert this window to a transient


window (temporary).

8 withdraw() It is used to delete the window but doesn't destroy it.

9 maxsize(width, It is used to declare the maximum size for the window.


height)

10 minsize(width, It is used to declare the minimum size for the window.


height)

11 positionfrom(who) It is used to define the position controller.

12 resizable(width, It is used to control whether the window can be


height) resizable or not.

13 sizefrom(who) It is used to define the size controller.

14 title(string) It is used to define the title for the window.

Example

1. from tkinter import *


2.
3. root = Tk()
4.
5. root.geometry("200x200")
6.
7. def open():
8. top = Toplevel(root)
9. top.mainloop()
10.
11. btn = Button(root, text = "open", command = open)
12.
13. btn.place(x=75,y=50)
14.
15. root.mainloop()

Output:
9.3. Tkinter Label

A Label is a Tkinter Widget class, which is used to display text or an image. The label is a
widget that the user just views but not interact with.

There is hardly any book or introduction into a programming language, which doesn't
start with the "Hello World" example. We will draw on tradition but will slightly modify
the output to "Hello Tkinter" instead of "Hello World".

The following Python script uses Tkinter to create a window with the text "Hello Tkinter".
You can use the Python interpretor to type this script line after line, or you can save it in
a file, for example, "hello.py":

import tkinter as tk

root = tk.Tk()
w = tk.Label(root, text="Hello Tkinter!")
w.pack()

root.mainloop()
Under Windows it appears in the Windows look and feel:

Explanation
The tkinter module, containing the Tk toolkit, has always to be imported. In our example,
we imported tkinter by renaming it into tk, which is the preferred way to do it:

import tkinter as tk

To initialize tkinter, we have to create a Tk root widget, which is a window with a title bar
and other decoration provided by the window manager. The root widget has to be created
before any other widgets and there can only be one root widget.

root = tk.Tk()

The next line of code contains the Label widget. The first parameter of the Label call is the
name of the parent window, in our case "root". So our Label widget is a child of the root
widget. The keyword parameter "text" specifies the text to be shown:

w = tk.Label(root, text="Hello Tkinter!")

The pack method tells Tk to fit the size of the window to the given text.

w.pack()

The window won't appear until we enter the Tkinter event loop:

root.mainloop()

Our script will remain in the event loop until we close the window.
9.4. Dialogues and Message Boxes

Tkinter (and TK of course) provides a set of dialogues (dialogs in American English


spelling), which can be used to display message boxes, showing warning or errors, or
widgets to select files and colours. There are also simple dialogues, asking the user to
enter string, integers or float numbers.

Let's look at a typical GUI Session with Dialogues and Message boxes. There might be a
button starting the dialogue, like the "quit" button in the following window:

Pushing the "quit" button raises the Verify window:

Let's assume that we want to warn users that the "quit" functionality is not yet
implemented. In this case we can use the warning message to inform the user, if he or she
pushes the "yes" button:

If somebody types the "No" button, the "Cancel" message box is raised:
Let's go back to our first Dialogue with the "quit" and "answer" buttons. If the "Answer"
functionality is not implemented, it might be useful to use the following error message
box:

Python script, which implements the previous dialogue widges:

import tkinter as tk
from tkinter import messagebox as mb
Def answer():
mb.showerror("Answer", "Sorry, no answer available")

def callback():
if mb.askyesno('Verify', 'Really quit?'):
mb.showwarning('Yes', 'Not yet implemented')
else:
mb.showinfo('No', 'Quit has been cancelled')

tk.Button(text='Quit', command=callback).pack(fill=tk.X)
tk.Button(text='Answer', command=answer).pack(fill=tk.X)
tk.mainloop()

Message Boxes

The message dialogues are provided by the 'messagebox' submodule of tkinter.

'messagebox' consists of the following functions, which correspond to dialog windows:

 askokcancel(title=None, message=None, **options)


Ask if operation should proceed; return true if the answer is ok
 askquestion(title=None, message=None, **options)
Ask a question
 askretrycancel(title=None, message=None, **options)
Ask if operation should be retried; return true if the answer is yes
 askyesno(title=None, message=None, **options)
Ask a question; return true if the answer is yes
 askyesnocancel(title=None, message=None, **options)
Ask a question; return true if the answer is yes, None if cancelled.
 showerror(title=None, message=None, **options)
Show an error message
 showinfo(title=None, message=None, **options)
Show an info message
 showwarning(title=None, message=None, **options)
Show a warning message

Message Widget

The widget can be used to display short text messages. The message widget is similar in
its functionality to the Label widget, but it is more flexible in displaying text, e.g. the font
can be changed while the Label widget can only display text in a single font. It provides a
multiline object, that is the text may span more than one line. The text is automatically
broken into lines and justified. We were ambiguous, when we said, that the font of the
message widget can be changed. This means that we can choose arbitrarily a font for one
widget, but the text of this widget will be rendered solely in this font. This means that we
can't change the font within a widget. So it's not possible to have a text in more than one
font. If you need to display text in multiple fonts, we suggest to use a Text widget.

The syntax of a message widget:

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


Let's have a look at a simple example. The following script creates a message with a
famous saying by Mahatma Gandhi:

import tkinter as tk
master = tk.Tk()
whatever_you_do = "Whatever you do will be insignificant, but it is very important th
at you do it.\n(Mahatma Gandhi)"
msg = tk.Message(master, text = whatever_you_do)
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.pack()
tk.mainloop()

The widget created by the script above looks like this:

The Options in Detail

Option Meaning

anchor The position, where the text should be placed in the message
widget: N, NE, E, SE, S, SW, W, NW, or CENTER. The Default is
CENTER.
aspect Aspect ratio, given as the width/height relation in percent. The
default is 150, which means that the message will be 50% wider
than it is high. Note that if the width is explicitly set, this option
is ignored.

background The background color of the message widget. The default value
is system specific.

bg Short for background.

borderwidth Border width. Default value is 2.

bd Short for borderwidth.

cursor Defines the kind of cursor to show when the mouse is moved
over the message widget. By default the standard cursor is
used.

font Message font. The default value is system specific.

foreground Text color. The default value is system specific.

Fg Same as foreground.

highlightbackground Together with highlightcolor and highlightthickness, this


option controls how to draw the highlight region.

highlightcolor See highlightbackground.

highlightthickness See highlightbackground.

justify Defines how to align multiple lines of text. Use LEFT, RIGHT, or
CENTER. Note that to position the text inside the widget, use
the anchor option. Default is LEFT.

padx Horizontal padding. Default is -1 (no padding).

pady Vertical padding. Default is -1 (no padding).

relief Border decoration. The default is FLAT. Other possible values


are SUNKEN, RAISED, GROOVE, and RIDGE.

takefocus If true, the widget accepts input focus. The default is false.

text Message text. The widget inserts line breaks if necessary to get
the requested aspect ratio. (text/Text)
textvariable Associates a Tkinter variable with the message, which is usually
a StringVar. If the variable is changed, the message text is
updated.

width Widget width given in character units. A suitable width based


on the aspect setting is automatically chosen, if this option is
not given.

9.5. Entry Widgets

Entry widgets are the basic widgets of Tkinter used to get input, i.e. text strings, from the
user of an application. This widget allows the user to enter a single line of text. If the user
enters a string, which is longer than the available display space of the widget, the content
will be scrolled. This means that the string cannot be seen in its entirety. The arrow keys
can be used to move to the invisible parts of the string. If you want to enter multiple lines
of text, you have to use the text widget. An entry widget is also limited to single font.

The syntax of an entry widget looks like this:

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

"master" represents the parent window, where the entry widget should be placed. Like
other widgets, it's possible to further influence the rendering of the widget by using
options. The comma separated list of options can be empty.

The following simple example creates an application with two entry fields. One for
entering a last name and one for the first name. We use Entry without options.

import tkinter as tk

master = tk.Tk()
tk.Label(master, text="First Name").grid(row=0)
tk.Label(master, text="Last Name").grid(row=1)
e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

master.mainloop()

The window created by the previous script looks like this:

Okay, we have created Entry fields, so that the user of our program can put in some data.
But how can our program access this data? How do we read the content of an Entry?

To put it in a nutshell: The get() method is what we are looking for. We extend our little
script by two buttons "Quit" and "Show". We bind the function show_entry_fields(), which
is using the get() method on the Entry objects, to the Show button. So, every time this
button is clicked, the content of the Entry fields will be printed on the terminal from which
we had called the script.

import tkinter as tk

def show_entry_fields():
print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))

master = tk.Tk()
tk.Label(master,
text="First Name").grid(row=0)
tk.Label(master,
text="Last Name").grid(row=1)
e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

tk.Button(master,
text='Quit',
command=master.quit).grid(row=3,
column=0,
sticky=tk.W,
pady=4)
tk.Button(master,
text='Show', command=show_entry_fields).grid(row=3,
column=1,
sticky=tk.W,
pady=4)

tk.mainloop()

The complete application looks now like this:

Let's assume now that we want to start the Entry fields with default values, e.g. we fill in
"Miller" or "Baker" as a last name, and "Jack" or "Jill" as a first name. The new version of
our Python program gets the following two lines, which can be appended after the Entry
definitions, i.e. "e2 = tk.Entry(master)":
e1.insert(10, "Miller")
e2.insert(10, "Jill")

What about deleting the input of an Entry object, every time, we are showing the content
in our function show_entry_fields()? No problem! We can use the delete method. The
delete() method has the format delete(first, last=None). If only one number is given, it
deletes the character at index. If two are given, the range from "first" to "last" will be
deleted. Use delete(0, END) to delete all text in the widget.

import tkinter as tk

def show_entry_fields():
print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))
e1.delete(0, tk.END)
e2.delete(0, tk.END)

master = tk.Tk()
tk.Label(master, text="First Name").grid(row=0)
tk.Label(master, text="Last Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)
e1.insert(10, "Miller")
e2.insert(10, "Jill")

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
tk.Button(master,
text='Quit',
command=master.quit).grid(row=3,
column=0,
sticky=tk.W,
pady=4)
tk.Button(master, text='Show', command=show_entry_fields).grid(row=3,
column=1,
sticky=tk.W,
pady=4)

master.mainloop()

tk.mainloop()

The next example shows, how we can elegantly create lots of Entry field in a more
Pythonic way. We use a Python list to hold the Entry descriptions, which we include as
labels into the application.

import tkinter as tk

fields = 'Last Name', 'First Name', 'Job', 'Country'

def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))

def makeform(root, fields):


entries = []
for field in fields:
row = tk.Frame(root)
lab = tk.Label(row, width=15, text=field, anchor='w')
ent = tk.Entry(row)
row.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
lab.pack(side=tk.LEFT)
ent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)
entries.append((field, ent))
return entries

if __name__ == '__main__':
root = tk.Tk()
ents = makeform(root, fields)
root.bind('<Return>', (lambda event, e=ents: fetch(e)))
b1 = tk.Button(root, text='Show',
command=(lambda e=ents: fetch(e)))
b1.pack(side=tk.LEFT, padx=5, pady=5)
b2 = tk.Button(root, text='Quit', command=root.quit)
b2.pack(side=tk.LEFT, padx=5, pady=5)
root.mainloop()

If you start this Python script, it will look like this:


9.6. ListBox Widget

Tkinter is a GUI toolkit used in python to make user-friendly GUIs.Tkinter is the most
commonly used and the most basic GUI framework available in python. Tkinter uses an
object-oriented approach to make GUIs.

The ListBox widget is used to display different types of items. These items must be of
the same type of font and having the same font color. The items must also be of Text
type. The user can select one or more items from the given list according to the
requirement.
Syntax:
listbox = Listbox(root, bg, fg, bd, height, width, font, ..)
Optional parameters

 root – root window.


 bg – background colour
 fg – foreground colour
 bd – border
 height – height of the widget.
 width – width of the widget.
 font – Font type of the text.
 highlightcolor – The colour of the list items when focused.
 yscrollcommand – for scrolling vertically.
 xscrollcommand – for scrolling horizontally.
 cursor – The cursor on the widget which can be an arrow, a dot etc.
Common methods
 yview – allows the widget to be vertically scrollable.
 xview – allows the widget to be horizontally scrollable.
 get() – to get the list items in a given range.
 activate(index) – to select the lines with a specified index.
 size() – return the number of lines present.
 delete(start, last) – delete lines in the specified range.
 nearest(y) – returns the index of the nearest line.
 curseselection() – returns a tuple for all the line numbers that are being selected.
Example 1:

from tkinter import *


top = Tk()
# create listbox object
listbox = Listbox(top, height = 10,
width = 15,
bg = "grey",
activestyle = 'dotbox',
font = "Helvetica",
fg = "yellow")

# Define the size of the window.


top.geometry("300x250")

# Define a label for the list.


label = Label(top, text = " FOOD ITEMS")

# insert elements by their


# index and names.
listbox.insert(1, "Nachos")
listbox.insert(2, "Sandwich")
listbox.insert(3, "Burger")
listbox.insert(4, "Pizza")
listbox.insert(5, "Burrito")

# pack the widgets


label.pack()
listbox.pack()

# Display untill User


# exits themselves.
top.mainloop()
Output

9.7. Tkinter Buttons

The Button widget is a standard Tkinter widget, which is used for various kinds of
buttons. A button is a widget which is designed for the user to interact with, i.e. if the
button is pressed by mouse click some action might be started. They can also contain text
and images like labels. While labels can display text in various fonts, a button can only
display text in a single font. The text of a button can span more than one line.

A Python function or method can be associated with a button. This function or method
will be executed, if the button is pressed in some way.

Example for the Button Class

The following script defines two buttons: one to quit the application and another one for
the action, i.e. printing the text "Tkinter is easy to use!" on the terminal.

import tkinter as tk
Def write_slogan():
print("Tkinter is easy to use!")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()

button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)

root.mainloop()

The result of the previous example looks like this:

Dynamical Content in a Label

The following script shows an example, where a label is dynamically incremented by 1


until a stop button is pressed:

import tkinter as tk

counter = 0
def counter_label(label):
counter = 0
def count():
global counter
counter += 1
label.config(text=str(counter))
label.after(1000, count)
count()
Root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="dark green")
label.pack()
counter_label(label)

button = tk.Button(root, text='Stop', width=25, command=root.destroy)


button.pack()
root.mainloop()

The result of the previous example looks like this:

9.8. Radio Buttons

A radio button, sometimes called option button, is a graphical user interface element of
Tkinter, which allows the user to choose (exactly) one of a predefined set of options.
Radio buttons can contain text or images. The button can only display text in a single font.
A Python function or method can be associated with a radio button. This function or
method will be called, if you press this radio button.

Radio buttons are named after the physical buttons used on old radios to select wave
bands or preset radio stations. If such a button was pressed, other buttons would pop out,
leaving the pressed button the only pushed in button.
Each group of Radio button widgets has to be associated with the same variable. Pushing
a button changes the value of this variable to a predefined certain value.

Simple Example With Radio Buttons

import tkinter as tk

Root = tk.Tk()
V = tk.IntVar()
tk.Label(root,
text="""Choose a
programming language:""",
justify = tk.LEFT,
padx = 20).pack()
tk.Radiobutton(root,
text="Python",
padx = 20,
variable=v,
value=1).pack(anchor=tk.W)

tk.Radiobutton(root,
text="Perl",
padx = 20,
variable=v,
value=2).pack(anchor=tk.W)

root.mainloop()

The result of the previous example looks like this:


9.9. Checkboxes

Checkboxes, also known as tickboxes or tick boxes or check boxes, are widgets that
permit the user to make multiple selections from a number of different options. This is
different to a radio button, where the user can make only one choice.

Usually, checkboxes are shown on the screen as square boxes that can contain white
spaces (for false, i.e not checked) or a tick mark or X (for true, i.e. checked).

A caption describing the meaning of the checkbox is usually shown adjacent to the
checkbox. The state of a checkbox is changed by clicking the mouse on the box.
Alternatively it can be done by clicking on the caption, or by using a keyboard shortcut,
for example, the space bar.

A Checkbox has two states: on or off.

The Tkinter Checkbutton widget can contain text, but only in a single font, or images, and
a button can be associated with a Python function or method. When a button is pressed,
Tkinter calls the associated function or method. The text of a button can span more than
one line.

Simple Example

The following example presents two checkboxes "male" and "female". Each checkbox
needs a different variable name (IntVar()).

from tkinter import *


master = Tk()
var1 = IntVar()
Checkbutton(master, text="male", variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text="female", variable=var2).grid(row=1, sticky=W)
mainloop()

If we start this script, we get the following window:

9.10. Sliders

a slider is a Tkinter object with which a user can set a value by moving an indicator.
Sliders can be vertically or horizontally arranged. A slider is created with the Scale
method().

Using the Scale widget creates a graphical object, which allows the user to select a
numerical value by moving a knob along a scale of a range of values. The minimum and
maximum values can be set as parameters, as well as the resolution. We can also
determine if we want the slider vertically or horizontally positioned. A Scale widget is a
good alternative to an Entry widget, if the user is supposed to put in a number from a
finite range, i.e. a bounded numerical value.

A Simple Example

from Tkinter import *

master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()

If we start this script, we get a window with a vertical and a horizontal slider:

Accessing Slider Values

We have demonstrated in the previous example how to create sliders. But it's not enough
to have a slider, we also need a method to query it's value. We can accomplish this with
the get method. We extend the previous example with a Button to view the values. If this
button is pushed, the values of both sliders is printed into the terminal from which we
have started the script:

from Tkinter import *


def show_values():
print (w1.get(), w2.get())
Master = Tk()
w1 = Scale(master, from_=0, to=42)
w1.pack()
w2 = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w2.pack()
Button(master, text='Show', command=show_values).pack()

mainloop()
Initializing Sliders
A slider starts with the minimum value, which is 0 in our examples. There is a way to
initialize Sliders with the set(value) method:

from Tkinter import *

def show_values():
print (w1.get(), w2.get())

master = Tk()
w1 = Scale(master, from_=0, to=42)
w1.set(19)
w1.pack()
w2 = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w2.set(23)
w2.pack()
Button(master, text='Show', command=show_values).pack()

mainloop()

The previous script creates the following window, if it is called:


9.11. Text Widgets

A text widget is used for multi-line text area. The tkinter text widget is very powerful and
flexible and can be used for a wide range of tasks. Though one of the main purposes is to
provide simple multi-line areas, as they are often used in forms, text widgets can also be
used as simple text editors or even web browsers.

Furthermore, text widgets can be used to display links, images, and HTML, even using CSS
styles.

In most other tutorials and text books, it's hard to find a very simple and basic example
of a text widget. That's why we want to start our chapter with a such an example:

We create a text widget by using the Text() method. We set the height to 2, i.e. two lines
and the width to 30, i.e. 30 characters. We can apply the method insert() on the object T,
which the Text() method had returned, to include text. We add two lines of text.

import tkinter as tk

root = tk.Tk()
T = tk.Text(root, height=2, width=30)
T.pack()
T.insert(tk.END, "Just a text Widget\nin two lines\n")
tk.mainloop()

The result should not be very surprising:

Let's change our little example a tiny little bit. We add another text, the beginning of the
famous monologue from Hamlet:

import tkinter as tk
root = tk.Tk()
T = tk.Text(root, height=10, width=30)
T.pack()
quote = """HAMLET: To be, or not to be--that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune
Or to take arms against a sea of troubles
And by opposing end them. To die, to sleep--
No more--and by a sleep to say we end
The heartache, and the thousand natural shocks
That flesh is heir to. 'Tis a consummation
Devoutly to be wished."""
T.insert(tk.END, quote)
tk.mainloop()

If we start our little script, we get a very unsatisfying result. We can see in the window
only the first line of the monologue and this line is even broken into two lines. We can see
only two lines in our window, because we set the height to the value 2. Furthermore, the
width is set to 30, so tkinter has to break the first line of the monologue after 30
characters.

One solution to our problem consists in setting the height to the number of lines of our
monologue and set width wide enough to display the widest line completely.

But there is a better technique, which you are well acquainted with from your browser
and other applications: scrolling
9.12. Scrollbars

So let's add a scrollbar to our window. To this purpose, Tkinter provides the Scrollbar()
method. We call it with the root object as the only parameter.

import tkinter as tk

root = tk.Tk()
S = tk.Scrollbar(root)
T = tk.Text(root, height=4, width=50)
S.pack(side=tk.RIGHT, fill=tk.Y)
T.pack(side=tk.LEFT, fill=tk.Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
quote = """HAMLET: To be, or not to be--that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune
Or to take arms against a sea of troubles
And by opposing end them. To die, to sleep--
No more--and by a sleep to say we end
The heartache, and the thousand natural shocks
That flesh is heir to. 'Tis a consummation
Devoutly to be wished."""

T.insert(tk.END, quote)
tk.mainloop()

The result is a lot better. We have now always 4 lines in view, but all lines can be viewed
by using the scrollbar on the right side of the window:
Text Widget with Image

In our next example, we add an image to the text and bind a command to a text line:

import tkinter as tk

root = tk.Tk()

text1 = tk.Text(root, height=20, width=30)


photo = tk.PhotoImage(file='./William_Shakespeare.gif')
text1.insert(tk.END, '\n')
text1.image_create(tk.END, image=photo)

text1.pack(side=tk.LEFT)

text2 = tk.Text(root, height=20, width=50)


scroll = tk.Scrollbar(root, command=text2.yview)
text2.configure(yscrollcommand=scroll.set)
text2.tag_configure('bold_italics', font=('Arial', 12, 'bold', 'italic'))
text2.tag_configure('big', font=('Verdana', 20, 'bold'))

text2.tag_configure('color',
foreground='#476042',
font=('Tempus Sans ITC', 12, 'bold'))
text2.tag_bind('follow',
'<1>',
lambda e, t=text2: t.insert(tk.END, "Not now, maybe later!"))
text2.insert(tk.END,'\nWilliam Shakespeare\n', 'big')
quote = """
To be, or not to be that is the question:
Whether 'tis Nobler in the mind to suffer
The Slings and Arrows of outrageous Fortune,
Or to take Arms against a Sea of troubles,
"""
text2.insert(tk.END, quote, 'color')
text2.insert(tk.END, 'follow-up\n', 'follow')
text2.pack(side=tk.LEFT)
scroll.pack(side=tk.RIGHT, fill=tk.Y)

root.mainloop()

9.13. Menus
Most people, if confronted with the word "menu", will immediately think of a menu in a
restaurant. Even though the menu of a restaurant and the menu of a computer program
have at first glance nothing in common, we can see that yet the have a lot in common. In
a restaurant, a menu is a presentation of all their food and beverage offerings, while in a
computer application it presents all the commands and functions of the application,
which are available to the user via the grafical user interface.
<br< the="" choices="" offered="" by="" a="" menu="" may="" be="" selected="" user=""
in="" various="" ways,="" e.g.="" typing="" keys="" or="" combination="" of="" on=""
keyboard,="" clicking="" mouse="" buttons,="" touching="" display="" screen="" with=""
fingers.=""

Menus in GUIs are presented with a combination of text and symbols to represent the
choices. Selecting with the mouse (or finger on touch screens) on one of the symbols or
text, an action will be started. Such an action or operation can, for example, be the opening
or saving of a file, or the quitting or exiting of an application.

A context menu is a menu in which the choices presented to the user are modified
according to the current context in which the user is located.

We introduce in this chapter of our Python Tkinter tutorial the pull-down menus of
Tkinter, i.e. the lists at the top of the windows, which appear (or pull down), if you click
on an item like, for example "File", "Edit" or "Help".

A Simple Menu Example

The following Python script creates a simple application window with menus.

from tkinter import *


from tkinter.filedialog import askopenfilename

def NewFile():
print("New File!")
def OpenFile():
name = askopenfilename()
print(name)
def About():
print("This is a simple example of a menu")
root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=NewFile)
filemenu.add_command(label="Open...", command=OpenFile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)

helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=About)

mainloop()

It looks like this, if started:


10.1. Events and Binds

A Tkinter application runs most of its time inside an event loop, which is entered via the
mainloop method. It waiting for events to happen. Events can be key presses or mouse
operations by the user.

Tkinter provides a mechanism to let the programmer deal with events. For each widget,
it's possible to bind Python functions and methods to an event.

widget.bind(event, handler)

If the defined event occurs in the widget, the "handler" function is called with an event
object. describing the event.

from tkinter import *


def hello(event):
print("Single Click, Button-l")
def quit(event):

print("Double Click, so let's stop")


import sys; sys.exit()
widget = Button(None, text='Mouse Clicks')
widget.pack()
widget.bind('<Button-1>', hello)
widget.bind('<Double-1>', quit)
widget.mainloop()

Let's have another simple example, which shows how to use the motion event, i.e. if the
mouse is moved inside of a widget:

from tkinter import *

def motion(event):
print("Mouse position: (%s %s)" % (event.x, event.y))
return
master = Tk()
whatever_you_do = "Whatever you do will be insignificant, but it is very important th
at you do
it.\n(Mahatma Gandhi)"
msg = Message(master, text = whatever_you_do)
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.bind('<Motion>',motion)
msg.pack()
mainloop()

Every time we move the mouse in the Message widget, the position of the mouse pointer
will be printed. When we leave this widget, the function motion() is not called anymore.

10.2. Events

Tkinter uses so-called event sequences for allowing the user to define which events, both
specific and general, he or she wants to bind to handlers. It is the first argument "event"
of the bind method. The event sequence is given as a string, using the following syntax:

<modifier-type-detail>

The type field is the essential part of an event specifier, whereas the "modifier" and
"detail" fields are not obligatory and are left out in many cases. They are used to provide
additional information for the chosen "type". The event "type" describes the kind of event
to be bound, e.g. actions like mouse clicks, key presses or the widget got the input focus.

Event Description
<Button> A mouse button is pressed with the mouse pointer over the widget.
The detail part specifies which button, e.g. The left mouse button is
defined by the event <Button-1>, the middle button by <Button-2>,
and the rightmost mouse button by <Button-3>.
<Button-4> defines the scroll up event on mice with wheel support
and and <Button-5> the scroll down.
If you press down a mouse button over a widget and keep it
pressed, Tkinter will automatically "grab" the mouse pointer.
Further mouse events like Motion and Release events will be sent
to the current widget, even if the mouse is moved outside the
current widget. The current position, relative to the widget, of the
mouse pointer is provided in the x and y members of the event
object passed to the callback. You can use ButtonPress instead of
Button, or even leave it out completely: , , and <1> are all synonyms.

<Motion> The mouse is moved with a mouse button being held down. To
specify the left, middle or right mouse button use <B1-Motion>,
<B2-Motion> and <B3-Motion> respectively. The current position
of the mouse pointer is provided in the x and y members of the
event object passed to the callback, i.e. event.x, event.y

<ButtonRelease> Event, if a button is released. To specify the left, middle or right


mouse button use <ButtonRelease-1>, <ButtonRelease-2>, and
<ButtonRelease-3> respectively. The current position of the mouse
pointer is provided in the x and y members of the event object
passed to the callback, i.e. event.x, event.y

<Double- Similar to the Button event, see above, but the button is double
Button> clicked instead of a single click. To specify the left, middle or right
mouse button use <Double-Button-1>, <Double-Button-2>, and
<Double-Button-3> respectively.
You can use Double or Triple as prefixes. Note that if you bind to
both a single click (<Button-1>) and a double click (<Double-
Button-1>), both bindings will be called.

<Enter> The mouse pointer entered the widget.


Attention: This doesn't mean that the user pressed the Enter key!.
<Return> is used for this purpose.

<Leave> The mouse pointer left the widget.

<FocusIn> Keyboard focus was moved to this widget, or to a child of this


widget.
<FocusOut> Keyboard focus was moved from this widget to another widget.

<Return> The user pressed the Enter key. You can bind to virtually all keys
on the keyboard: The special keys are Cancel (the Break key),
BackSpace, Tab, Return(the Enter key), Shift_L (any Shift key),
Control_L (any Control key), Alt_L (any Alt key), Pause, Caps_Lock,
Escape, Prior (Page Up), Next (Page Down), End, Home, Left, Up,
Right, Down, Print, Insert, Delete, F1, F2, F3, F4, F5, F6, F7, F8, F9,
F10, F11, F12, Num_Lock, and Scroll_Lock.

<Key> The user pressed any key. The key is provided in the char member
of the event object passed to the callback (this is an empty string
for special keys).

A The user typed an "a" key. Most printable characters can be used as
is. The exceptions are space (<space>) and less than (<less>). Note
that 1 is a keyboard binding, while <1> is a button binding.

<Shift-Up> The user pressed the Up arrow, while holding the Shift key pressed.
You can use prefixes like Alt, Shift, and Control.

<Configure> The size of the widget changed. The new size is provided in the
width and height attributes of the event object passed to the
callback. On some platforms, it can mean that the location changed.

10.3. Python interface for SQLite databases

Introduction to SQLite in Python


Databases offer numerous functionalities by which one can manage large amounts of
information easily over the web and high-volume data input and output over a typical
file such as a text file. SQL is a query language and is very popular in databases. Many
websites use MySQL. SQLite is a “light” version that works over syntax very much
similar to SQL. SQLite is a self-contained, high-reliability, embedded, full-featured,
public-domain, SQL database engine. It is the most used database engine on the world
wide web. Python has a library to access SQLite databases, called sqlite3, intended for
working with this database which has been included with Python package since version
2.5. SQLite has the following features.
1. Serverless
2. Self-Contained
3. Zero-Configuration
4. Transactional
5. Single-Database

Serverless

Generally, an RDBMS such as MySQL, PostgreSQL, etc., needs a separate server process
to operate. The applications that want to access the database server use TCP/IP
protocol to send and receive requests and it is called client/server architecture.

SQLite does not require a server to run. SQLite database is joined with the application
that accesses the database. SQLite database read and write directly from the database
files stored on disk and applications interact with that SQLite database.

Self-Contained

SQLite is self-contained means it does not need any external dependencies like an
operating system or external library. This feature of SQLite help especially in embedded
devices like iPhones, Android phones, game consoles, handheld media players, etc.
SQLite is developed using ANSI-C. The source code is available as a big sqlite3.c and its
header file sqlite3.h. If users want to develop an application that uses SQLite, users just
need to drop these files into your project and compile it with your code.

Zero-Configuration

SQLite is zero-configuration means no setup or administration needed. Because of the


serverless architecture, you don’t need to “install” SQLite before using it. There is no
server process that needs to be configured, started, and stopped.
Transactional

SQLite is Transactional means they are atomic, consistent, isolated, and durable(ACID).
All transactions in SQLite are fully ACID-compliant. In other words, all changes within a
transaction take place completely or not at all even when an unexpected situation like
application crash, power failure, or operating system crash occurs.

Single-Database

SQLite is a single database that means it allows a single database connection to access
multiple database files simultaneously. These features bring many nice features like
joining tables in different databases or copying data between databases in a single
command. SQLite also uses dynamic types for tables. It means you can store any value
in any column, regardless of the data type.
Understanding of SQLite Module Working in Python
Python SQLite is used to demonstrate how to develop Python database applications
with the SQLite database. You will learn how to perform SQLite database operations
from Python. SQLite comes built-in with most of the computers and mobile devices and
browsers. Python’s official sqlite3 module helps us to work with the SQLite database.

In this diagram, the Python sqlite3 module adheres to Python Database API
Specification v2.0 (PEP 249). PEP 249 provides a SQL interface that has been designed
to encourage and maintain the similarity between the Python modules that are used to
access databases.
SQLite and Python types
SQLite data types are by default mapped to equivalent Python data types as per following
table
Python type SQLite type

None NULL

Int INTEGER

Float REAL

Str TEXT

Bytes BLOB

Exceptions
The DB-API defines following exceptions with respect to SQL operations with a SQLite
database −

DatabaseError Exception raised for errors that are related to the database.

IntegrityError Exception raised when the relational integrity of the database is


affected, e.g. a foreign key check fails. It is a subclass of
DatabaseError.

ProgrammingError Exception raised for programming errors, e.g.table not found or


already exists, syntax error in the SQL statement, the wrong
number of parameters specified, etc.

OperationalError Exception raised for errors that are related to the database’s
operation and not necessarily under the control of the
programmer,

NotSupportedError Exception raised in case a method or database API was used which
is not supported by the database.
Python SQLite – Connecting to Database
Connecting to the SQLite Database can be established using the connect() method,
passing the name of the database to be accessed as a parameter. If that database does not
exist, then it’ll be created.
sqliteConnection = sqlite3.connect('sql.db')

Connect() function
This function in sqlite3 module returns connection object representing an existing
database on disk , or opens a new database if it doesn't exist already.

import sqlite3
conn=sqlite3.connect('mydb.sqlite3')

SQLite supports creation of in-memory database. Use a special name ':memory:' for that
purpose

conn=sqlite3.connect(':memory:')

Following methods are defined in Connection class

cursor() This method returns cursor object.

cur=conn.cursor()

commit() − This method persistently commits transactions to the disk.

rollback() − This method rolls back transactions to restore database state to last call to
commit(). This method ensures data consistency in case of exceptions in SQL
transactions.

try:
conn.commit()
except:
conn.rollback()

execute() − Implicitly creates cursor and calls its execute() method

executemany() − This method implicitly creates cursor and calls its executemany()
method

create_function() − This method creates a user-defined function that you can later use
from within SQL statements.

create_aggregate() − This method creates an aggregate function.


iterdump() − This method creates a dump of database in SQL text format.

import sqlite3
con = sqlite3.connect('mydb.sqlite3')
f = dump.sql', 'w')
for line in con.iterdump():
f.write('%s\n' % line)

backup() − This method creates a backup of SQLite database even while it is being
accessed.

source = sqlite3.connect('mydb.sqlite3')
dest = sqlite3.connect(':memory:')
source.backup(dest)
cursor object
Cursor obtained from connection object facilitates performing various SQL operations on
the database using execute() method. For instance, following statement creates a table in
the current database

cur = conn.cursor()
cur.execute("CREATE TABLE guests (
ID INTEGER PRIMARY KEY,
name TEXT (20) NOT NULL,
address TEXT (40),
city TEXT (20)
);"

Following inserts a record in the table

cur.execute('''INSERT INTO GUESTS VALUES(1,'RAJU','ABIDS', 'HYDERABAD');''')

Use executemany() method to perform bulk addition operation

addreses=[(2,'KISHAN', 'TILAK ROAD', 'PUNE'), (3, 'LATA', 'GAANDHI NAGAR',


'AURANGABAD')]
sql='INSERT INTO GUESTS VALUES (:ID, :NAME, :ADD, :CITY)'
cur.executemany(sql, addreses)

SELECT query forms a result set containing all records returned as a response to query.
The execute() method uses a string representing SELECT query statement. There are two
methods in DB-API to retrieve rows in the cursor representing the result set.

fetchone() − Fetches next available record from the result set in the form a tuple
consisting of values of each column of the fetched record.
fetchall() − Fetches all remaining records in the form of list of tuples. Each tuple
corresponds to one row and contains values of each column in the table.

Python SQLite – Cursor Object


A cursor has to be created using the cursor() method on the connection instance, which
will execute our SQL queries.
Cursor Object
It is an object that is used to make the connection for executing SQL queries. It acts as
middleware between SQLite database connection and SQL query. It is created after
giving connection to SQLite database.
Syntax: cursor_object=connection_object.execute(“sql query”);
Example 1: Python code to create a hotel_data database and insert records into the
hotel table.
# importing sqlite3 module
import sqlite3

# create connection by using object


# to connect with hotel_data database
connection = sqlite3.connect('hotel_data.db')

# query to create a table named FOOD1


connection.execute(''' CREATE TABLE hotel
(FIND INT PRIMARY KEY NOT NULL,
FNAME TEXT NOT NULL,
COST INT NOT NULL,
WEIGHT INT);
''')

# insert query to insert food details in


# the above table
connection.execute("INSERT INTO hotel VALUES (1, 'cakes',800,10 )")
connection.execute("INSERT INTO hotel VALUES (2, 'biscuits',100,20 )")
connection.execute("INSERT INTO hotel VALUES (3, 'chocos',1000,30 )")
print("All data in food table\n")
# create a cousor object for select query
cursor = connection.execute("SELECT * from hotel ")

# display all data from hotel table


for row in cursor:
print(row)
cursor = sqliteConnection.cursor()
print('DB Init')
The SQL query to be executed can be written in form of a string, and then executed by
calling the execute() method on the cursor object. Then, the result can be fetched from
the server by using the fetchall() method, which in this case, is the SQLite Version
Number.

query = 'SQL query;'


cursor.execute(query)
result = cursor.fetchall()
print('SQLite Version is {}'.format(result))
Consider the below example where we will connect to an SQLite database and will run a
simple query select sqlite_version(); to find the version of the SQLite we are using.
Example:

Example:
import sqlite3
con=sqlite3.connect("first.db")
cursor=con.cursor()
cursor.execute("create table if not exists first(Name text,id int)")
print("Table Created")
cursor.execute('''INSERT INTO first VALUES ('Raju', '7')''')
cursor.execute('''INSERT INTO first VALUES ('Shyam', '8')''')
cursor.execute('''INSERT INTO first VALUES ('Baburao', '9')''')

# Display data inserted


print("Data Inserted in the table: ")
data=cursor.execute('''SELECT * FROM first''')
for row in data:
print(row)

# Commit your changes in the database


conn.commit()

# Closing the connection


conn.close()

You might also like