Unit 5
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()
m.mainloop()
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.
Syntax
1. w = Toplevel(options)
A List of possible options is given below.
SN Options Description
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.
Methods
The methods associated with the Toplevel widget is given in the following list.
SN Method Description
Example
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:
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
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:
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:
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
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.
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()
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.
cursor Defines the kind of cursor to show when the mouse is moved
over the message widget. By default the standard cursor is
used.
Fg Same as foreground.
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.
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.
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.
"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()
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()
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
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
print('%s: "%s"' % (field, text))
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()
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
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.
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()
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)
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.
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()
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.
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()).
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
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:
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:
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:
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()
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()
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.pack(side=tk.LEFT)
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".
The following Python script creates a simple application window with menus.
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()
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.
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:
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
<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.
<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.
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 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.
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:')
cur=conn.cursor()
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()
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.
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)
);"
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.
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')''')