Scs 1619
Scs 1619
button
canvas
checkbutton
combobox
entry
frame
label
1
listbox
menu
message
progressbar
radiobutton
scrollbar
spinbox
text
1. Pack Layout
2. Grid Layout
3. Place Layout
2
It is a simple layout manager. Here widgets can be organized in
horizontal and vertical boxes. It is used to place each widget next to previous
widget. It will be called without any arguments and it will position and size
the widgets in a reasonable way. Whenever the user wants to have a series of
widgets in a vertical or horizontal row, the pack layout manager is fairly
simple to use. The layout is controlled with the fill, expand, and side options.
Example:
Output:
Explanation: Label l1 has been placed in top position, it is filled in X axis. Label
l2 has been placed in Right Position and it is also filled in X axis. Since
expand attribute has the value True for Label l1,it can be stretched.
3
Padding Option in Pack Layout:
The pack() manager has four padding options:
1. Internal Padding
2. External padding
3. Padding in X Direction.
4. Padding in Y Direction.
External Padding in Horizontal direction(padx)
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,padx=10)
l2.pack(fill=X,side=TOP,padx=10)
top.mainloop()
Output:
4
External Padding in Vertical direction (pady)
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,pady=10)
l2.pack(fill=X,side=TOP,pady=10)
top.mainloop()
Output:
5
Internal Padding in Horizontal direction(ipadx)
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,ipadx=10)
l2.pack(fill=X,side=TOP,ipadx=10)
top.mainloop()
Output:
Example:
fromtkinter import *
6
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l1.pack(fill=X,side=TOP,expand=True,ipadx=10)
l2.pack(fill=X,side=TOP,ipady=10)
top.mainloop()
Output:
7
l2=Label(top,text="Label2",bg="red" )
l1.place(x=10,y=50)
l2.place(x=10,y=100)
top.mainloop()
Output:
Explanation:
8
widgets but it is complex than pack. Grid is one of the most versatile layout
manager out of the three layout managers in python. By using Grid layout, the
widgets can be placed in rows and columns.
Example:
fromtkinter import *
top=Tk()
l1=Label(top,text="Label1",bg="blue")
l2=Label(top,text="Label2",bg="red" )
l3=Label(top,text="Label2",bg="green" )
l1.grid(row=0,column=0)
l2.grid(row=0,column=1)
l3.grid(row=1,column=1)
top.mainloop()
Output:
9
Explanation:
Here Label 1 is placed in 0th row and 0th column. Label 2 is placed in 0th row
and 1st column and Label 3 is placed in 1st row and 1st column.
3.3 FONT
3. By using XFont
10
Font can be specified using tuple.Herethe font tuple consists of
threeelements.First element specifies font family ,second element specifies
font size and third element specifies font style.
Ex: t =(“Arial”,14,”Bold”)
Example:
b1=Button(text="submit",font=("Arial","16","bold"))
b1.pack()
top.mainloop()
Output:
Explanation:
Text for the Button has been set in the Arial font with size 16 and Bold style.
11
Syntax for Font class constructor is:
Import tkFont
Font f1=tkFont.Font(parameters,…..)
Example:
fromtkinter import *
fromtkFont import *
top=Tk()
12
f1=Font(family="Helvetica",size=20,weight="bold",slant="italic",underline=1
,overstrike=1)
l1=Label(top,text="Label1",bg="blue",font=f1)
l1.pack()
top.mainloop()
X Window Fonts:
If you are running under the X Window System, you can use any of the X font
names.
3.4 COLORS
Tkinter represents colors with strings. There are two general ways to specify
colors in Tkinter :
We can use a string specifying the proportion of red, green and blue in
hexadecimal digits. For example,
"#fff" -- white,
"#000000" -- black,
"#000fff000" -- pure green
"#00ffff" -- pure cyan
We can also use any locally defined standard following color names.
"white"
"black"
13
"red"
"green"
"blue"
"cyan"
"yellow"
"magenta"
Active background − Specifies Background color for the widget when the
widget is active.
foreground − Specifies Foreground color for the widget. This can also
be represented as fg.
highlightbackground − Specifies Background color of the highlight region
14
when the widget has focus.
Example:
fromtkinter import *
top=Tk()
b1=Button(text="submit",bg="red",fg="white")
b1.pack()
top.mainloop()
Output:
Explanation:
15
Here the back ground of the button is red in color and foreground color of the
button is white in colour.
3.5 CANVAS
Syntax:
w = Canvas ( top, option=value, ... )
top – It represents the parent window.
Options − commonly used options for this widget. These options can be
used as key-value pairs separated by commas.
Commonly used Options are:
bd - Border Width of the canvas
bg - Background color of the canvas
cursor - Cursor used in the canvas like circle,arrow and dot.
relief - Type of the border
width - Width of the
canvas Items supported by canvas:
1. Arc
2. Image
3. Line
4. Oval
16
5. Polygon
ARC
Creates an arc item, which can be a chord or a simple arc.
Syntax:
Example:
w.pack()
Output:
17
Explanation:
Here Arc is drawn with blue color and within the bounded rectangle with top
left(10,50)position and bottom right(240,210) position and started from angle
0 and extended till 150 degree.
3.5.1 Image
Syntax:
Create_image(x,y,options….)
18
anchor=Where to place the image relative to the given position.
Default is CENTER.
image=image object
Example:
fromtkinter import *
root=Tk()
w = Canvas(root, width=500,
height=500) w.create_image("F:\
img2",50,50) w.pack()
root.mainloop()
3.5.2 Line
Syntax:
19
Example:
fromtkinter import *
root=Tk()
w.create_line(10,10,100,100,activefill="red")
w.pack()
root.mainloop()
Output:
3.5.3 Oval
20
Creates a circle or an ellipse at the given coordinates. It takes two pairs of
coordinates; the top left and bottom right corners of the bounding rectangle for
the oval.
Syntax:
x0, y0, x1, y1- the top left and bottom right corners of the bounding
rectangle
Options:
Example:
w.create_oval(10,10,100,100,activefill="red")
w.pack()
root.mainloop()
21
Output:
3.5.4 Polygon
Syntax:
polygon Options:
Example
fromtkinter import *
22
root=Tk()
w.create_polygon(50,50,20,20,100,100,activefill="red")
w.pack()
root.mainloop()
Widgets are standard graphical user interface (GUI) elements, like different
kinds of buttons and menus.
3.6.1 Label
A Label widget shows text to the user about other widgets used in the
application. The widget can be updated programmatically.
w=Label (root
Window
23
List of commonly used options are given below:
Option Description
anchor It specifies the exact position of the text within the size provided to
the widget. The default value is CENTER, which is used to center
the text within the specified space.
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor. eg: dot, arrow, circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text
24
Example:
fromtkinter import *
root=Tk()
l1.pack()
root,mainloop()
Output:
Explanation:
Here Label has been created with green background color and white
foreground color with the text “Enter User Name”.
25
ENTRY
The Entry widget is used to create the single line text-box to the user to
accept a value from the user. It can accept the text strings from the user. It can
receive one line of text from the user. For multiple lines of text, the text
widget will be used.
Widget: w=Entry(root,
options)
root-Main Window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
26
pady Vertical padding of text
Option Description
relief Specifies type of border
text Text to be displayed in the widget
undeline Underline the label text
selectbackground Background color of the selected text
selectforeground Foreground color of the selected text
show Specifies the character used to mask characters in the
text box
Example:
fromtkinter import *
root=Tk()
e1=Entry(root,show="*")
l1.pack(side=LEFT)
e1.pack(side=RIGHT)
root.mainloop()
27
Output:
28
Explanation:
Here Label and entry widgets are created.Since the show attribute value is
*,the characters entered in the text box appeared as “*”.
3.6.2 Button
Button Widget is used to create various kinds of buttons.The user can interact
with the button.They can contain text or images.
b=Button(root,options)
root-main window
29
Table 3.3: List of commonly used options for Button
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text
command It is set to function name which will be called the button is
clicked
Example:
fromtkinter import *
root=Tk()
30
b1=Button(root,text="Submit",bg="blue",fg="white")
b1.pack()
root.mainloop()
Output:
3.6.3 Checkbutton
b=CheckButton(root,options)
root-main window
31
Table 3.4: List of possible options for Checkbutton
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
undeline Underline the label text
command It is set to function name whicjh will be called the button is
clicked
offvalue Set value to the control variable if the button is
checked.Default Value is 1
onvalue Set value to the control variable if the button is
unchecked.Default Value is 0
selectcolor Set color of the check button when it is checked.
selectimage Set the image to be shown when it is checked.
Example:
fromtkinter import *
32
root=Tk()
c1.pack()
c2.pack()
c3.pack()
root.mainloop()
Output:
33
3.6.4 Radiobutton
b=RadioButton(root,options)
root-main window
34
Table 3.5: List of possible options for Radiobutton
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
text Text to be displayed in the widget
underline Underline the label text
command It is set to function name whicjh will be called the button
is clicked
value Set value to the control variable if the button is selected.
selectcolor Set color of the check button when it is checked.
selectimage Set the image to be shown when it is checked.
variable It is used to keep track of user choices.
34
Example:
fromtkinter import *
root=Tk()
10)
r1.pack()
r2.pack()
r3.pack()
root.mainloop()
Output:
35
36
3.6.5 Listbox
The Listbox widget is used to display the list items to the user.The user can
choose one or more items from the list depending upon the configuration.
Syntax for
creatingListBox:
b=Listbox(root,options)
root-main window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
37
pady Vertical padding of text
relief Specifies type of border
value Set value to the control variable if the button is selected.
selectbackground Set back ground color of the selected text.
xscrollcommand User can scroll the list box horizontally
yscrollcommand User can scroll the list box vertically
Example:
fromtkinter import *
top = Tk()
listbox = Listbox(top)
listbox.insert(1,"India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
listbox.insert(4, "Austrelia")
lbl.pack()
listbox.pack()
38
top.mainloop()
39
Output:
3.6.6 Message
Message:
m=Message(root,options)
root-main window
Option Description
Option Description
font Specifies font type of the text written inside the widget
Example:
fromtkinter import *
top = Tk()
msg.pack()
top.mainloop()
Output:
41
42
3.6.7 Text
Tkinter provides us the Entry widget which is used to implement the single
line text box. Text widget provides advanced capabilities that allow us to edit
a multiline text and format the way it has to be displayed, such as changing its
color and font. We can also use the structures like tabs and marks to locate
specific sections of the text, and apply changes to those areas.
Message:
T=Text(root,options)
root-main window
Option Description
43
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
cursor Specifies type of cursor.eg:dot,arrow,circle
font Specifies font type of the text written inside the widget
fg Foreground color of the widget
height Height of the widget
width Width of the widget
image Specifies image to be displayed in the widget
padx Horizontal padding of text
pady Vertical padding of text
relief Specifies type of border
xscrollcommand User can scroll the text widget horizontally
yscrollcommand User can scroll the text widget vertically
selectbackground Background color of the selected text
Description
Method
delete(startindex, This method is used to delete the characters of the
endindex) specified range
get(startindex,endindex) It returns the characters present in the specified
range.
44
insert(index, string) It is used to insert the specified string at the given
index.
Marks are used to bookmark the specified position between the characters of
the associated text.
Method Description
mark_set(mark,index) It is used to create mark at the specified index.
mark_unset(mark) It is used to clear the given mark
mark_names() It is used to return names of all the marks
The tags are the names given to the specific areas of the text. The tags are
used to configure the different areas of the text separately.
Method Description
tag_add(tagname, startindex, It is used to tag the characters in the
endindex) given range
45
tag_config() It is used to configure the tag properties
Example:
fromtkinter import *
top = Tk()
text = Text(top)
text.insert(INSERT, "Name....")
text.insert(END, "Salary.....")
text.pack()
Output:
46
Explanation:
The tag “Write Here” tags the characters from the index 0 to 4.The tag “Click
Here” tags the characters from the index 8 to 13.These tags are configured
using the method tag_config().
3.6.8 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which
can be used to select from a fixed number of values.
Syntax:
Parameters
1
activebackground
The color of the slider and arrowheads when the mouse is over them.
2
bg
The color of the slider and arrowheads when the mouse is not over them.
3
bd
The width of the 3-d borders around the entire perimeter of the trough,
and also the width of the 3-d effects on the arrowheads and slider.
Default is no border around the trough, and a 2-pixel border around
the arrowheads and slider.
48
4
command
A procedure to be called whenever the scrollbar is moved.
5
cursor
The cursor that appears when the mouse is over the scrollbar.
6
disabledbackground
The background color to use when the widget is disabled.
7
disabledforeground
The text color to use when the widget is disabled.
8
fg
Text color.
9
font
The font to use in this widget.
10
format
Format string. No default value.
49
11
from_
The minimum value. Used together with to to limit the spinbox
range.
12
justify
Default is LEFT
13
relief
Default is SUNKEN.
14
repeatdelay
Together with repeatinterval, this option controls button auto-
repeat. Both values are given in milliseconds.
15
repeatinterval
See repeatdelay.
16
state
One of NORMAL, DISABLED, or "readonly". Default is
NORMAL.
17
textvariable
50
No default value.
18
to
See from.
19
validate
Validation mode. Default is NONE.
20
validatecommand
Validation callback. No default value.
21
values
A tuple containing valid values for this widget. Overrides
from/to/increment.
22
vcmd
Same as validatecommand.
23
width
Widget width, in character units. Default is 20.
51
24
wrap
If true, the up and down buttons will wrap around.
25
xscrollcommand
Used to connect a spinbox field to a horizontal scrollbar. This
option should be set to the set method of the corresponding
scrollbar.
Methods
1
delete(startindex [,endindex])
This method deletes a specific character or a range of text.
2
get(startindex [,endindex])
This method returns a specific character or a range of text.
3
identify(x, y)
52
Identifies the widget element at the given location.
4
index(index)
Returns the absolute value of an index based on the given index.
5
insert(index [,string]...)
This method inserts strings at the specified index location.
6
invoke(element)
Invokes a spinbox button.
Example
master = Tk()
53
w = Spinbox(master, from_=0, to=10)
w.pack()
mainloop()
Example:
fromtkinter import *
top = Tk()
spin.pack()
top.mainloop()
Output:
54
3.7 FRAME
Frame widget is used to organize the group of widgets. It acts like a container
which can be used to hold the other widgets. The rectangular areas of the
screen are used to organize the widgets to the python application.
S=Frame(root,options)
root-main window
Option Description
bg Specifies background color of the widget
bd Specifies border width. Default is 2 pixels
55
cursor Specifies type of cursor.eg:dot,arrow,circle
height Height of the widget
width Width of the widget
Relief Specifies type of border
Example:
fromtkinter import *
top = Tk()
Topframe = Frame(top)
Topframe.pack(side = TOP)
Bottomframe = Frame(top)
Bottomframe.pack(side =BOTTOM)
btn1 = Button(Topframe, text="Submit", fg="red",activebackground = "red")
btn1.pack(side = LEFT)
btn2 = Button(Topframe, text="Remove", fg="brown", activebackground =
"brown")
btn2.pack(side = RIGHT)
btn3 = Button(Bottomframe, text="Add", fg="blue", activebackground =
"blue")
btn3.pack(side = LEFT)
56
btn4 = Button(Bottomframe, text="Modify", fg="black", activebackground =
"white")
btn4.pack(side = RIGHT)
top.mainloop()
Output:
Explanation:
Here two frames (Top Frame and Bottom Frame) have been
created.Topframe contains submit and remove buttons and Bottom frame
contains Add and modify buttons .
Binding function is used to deal with the events. We can bind Python’s
Functions and methods to an event as well as we can bind these functions to
any particular widget. Events can come from various sources, including key
presses and mouse operations by the user. Tkinter provides a powerful
57
mechanism to let you deal with events yourself. For each widget, you
can bind Python functions and methods to events.
widget.bind(event, handler)
A Tkinter application spends most of its time inside an event loop (entered via
the mainloop method). Events can come from various sources, including key
presses and mouse operations by the user, and redraw events from the window
manager.
Tkinter provides a powerful mechanism to deal with events. For each
widget, you can bind Python functions and methods to events.
widget.bind(event, handler)
If an event matching the event description occurs in the widget, the
given handler is called with an object describing the event.
Here’s a simple example:
Example Program1:Capturing clicks in a window
from tkinter import *
window = Tk()
def callback(event):
print ("clicked at", event.x, event.y)
frame = Frame(window, width=100, height=100)
frame.bind("<Button-1>", callback)
frame.pack()
window.mainloop()
58
In this example, the bind method of the frame widget is used to bind a
callback function to an event called <Button-1>. Run this program and click
in the window that appears. Each time you click, a message like “clicked at
44 63” is printed to the console window.
Keyboard events are sent to the widget that currently owns the
keyboard focus. The focus_set method can be used to move focus to a
widget:
Example Program2:Capturing keyboard events
from tkinter import *
window = Tk()
def key(event):
print("pressed", repr(event.char))
def callback(event):
frame.focus_set()
print("clicked at", event.x, event.y)
frame = Frame(window, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
window.mainloop()
If you run this script, you’ll find that you have to click in the frame before it
starts receiving any keyboard events.
Some of the commonly used events and some event properties are listed
below:
59
Table 3.15: Events
Event Description
<Bi-Motion> An event occurs when a mouse button is moved while
being held down on the widget.
<Button-i> Button-1, Button-2, and Button-3 identify the left,
middle, and right buttons. When a mouse buttonis
pressed over the widget, Tkinter automatically grabs
the mouse pointer’s location. ButtonPressed-
iissynonymous with Button-i.
<ButtonReleased- An event occurs when a mouse button is released.
i>
<Double-Button-i> An event occurs when a mouse button is double-
clicked.
<Enter> An event occurs when a mouse pointer enters the
widget.
<Key> An event occurs when a key is pressed.
<Leave> An event occurs when a mouse pointer leaves the
widget.
<Return> An event occurs when the Enter key is pressed. You
can bind any key such as A, B, Up, Down, Left, Right
in the keyboard with an event.
<Shift+A> An event occurs when the Shift+Akeys are pressed.
You can combine Alt, Shift, and Control with other
keys.
<Triple-Button-i> An event occurs when a mouse button is triple-clicked.
60
Table 3.16: Event Properties
61
Example Program3 : MouseKeyEventDemo
from tkinter import * # Import all definitions from tkinter
class MouseKeyEventDemo:
def init (self):
window = Tk() # Create a window
window.title("Event Demo") # Set a title
canvas = Canvas(window, bg = "white", width = 200, height = 100)
canvas.pack()
# Bind with <Button-1> event
canvas.bind("<Button-1>",
self.processMouseEvent)
# Bind with <Key> event
canvas.bind("<Key>", self.processKeyEvent)
canvas.focus_set()
window.mainloop() # Create an event loop
def processMouseEvent(self, event):
print("clicked at", event.x, event.y)
print("Position in the screen", event.x_root, event.y_root)
print("Which button is clicked? ", event.num)
def processKeyEvent(self, event):
print("keysym? ", event.keysym)
print("char? ", event.char)
print("keycode? ", event.keycode)
MouseKeyEventDemo() # Create GUI
62
Figure 1 a Output Window of Program3
The program creates a canvas and binds a mouse event <Button-1>with the
callbackfunction processMouseEventon the canvas. Nothing is drawn on the
canvas.So it is blank as shown in Figure 1a. When the left mouse button is
clicked on the canvas,an event is created. The processMouseEventis invoked
to process an event that displaysthe mouse pointer’s location on the canvas, on
63
the screen, and which mousebutton is clicked.The Canvas widget is also the
source for the key event. The program binds a key eventwith the callback
function processKeyEventon the canvas and sets the focus onthe canvas so
that the canvas will receive input from the keyboard.
The example Program EnlargeShrinkCircledisplays a circle on the canvas.
The circle radius is increased with a left mouseclick and decreased with a
right mouse click, as shown in Figure 2 a,2 b, 2c.
64
Example Program4 : EnlargeShrinkCircle
from tkinter import * # Import all definitions from tkinter
class EnlargeShrinkCircle:
def init (self):
self.radius = 50
window = Tk() # Create a window
window.title("Control Circle Demo") # Set a title
self.canvas = Canvas(window, bg = "white",width = 200, height = 200)
self.canvas.pack()
self.canvas.create_oval(100 - self.radius, 100 - self.radius,100 + self.radius,
100 + self.radius, tags = "oval")
# Bind canvas with mouse events
self.canvas.bind("<Button-1>", self.increaseCircle)
self.canvas.bind("<Button-3>", self.decreaseCircle)
window.mainloop() # Create an event loop
def increaseCircle(self, event):
self.canvas.delete("oval")
if self.radius< 100:
self.radius += 2
self.canvas.create_oval(100 - self.radius, 100 - self.radius,100 + self.radius,
100 + self.radius, tags = "oval")
def decreaseCircle(self, event):
self.canvas.delete("oval")
if self.radius> 2:
self.radius -= 2
self.canvas.create_oval(100 - self.radius, 100 - self.radius,100 + self.radius,
100 + self.radius, tags = "oval")
EnlargeShrinkCircle() # Create GUI
65
Figure 2 a Output Window of Program4
66
Figure 2 c Circle Radius Shrinked using Right Mou
of Program4
The program creates a canvas and displays a circle on the canvas with an
initialradius of 50. The canvas is bound to a mouse event <Button-1>with
thehandler increaseCircleand to a mouse event <Button-3>with the
handlerdecreaseCircle. When the left mouse button is pressed, the
increaseCirclefunction is invoked to increase the radius and redisplay the
circle.When the right mouse button is pressed, the decreaseCirclefunction is
invoked todecrease the radius and redisplay the circle.
Another simple example is given below that shows how to use the motion
event, i.e. if the mouse is moved inside of a widget:
67
Example Program5 : MouseMove
from tkinter import *
def motion(event):
print("Mouse position: (%s %s)" % (event.x, event.y))
return
window = Tk()
display_message = "Python Programming and Machine Learning"
msg = Message(window, text = display_message)
msg.config(bg='lightgreen', font=('times', 24, 'italic'))
msg.bind('<Motion>',motion)
msg.pack()
mainloop()
Every time the mouse is moved in the Message widget, the position of the
mouse pointer will be printed.
Example:
fromtkinter import *
fromtkinter.ttk import *
# creates tkinter window or root window
root = Tk()
# function to be called when button-2 of mouse is pressed
def pressed2(event):
print('Button-2 pressed at x = % d, y = % d'%(event.x, event.y))
# function to be called when button-3 of mouse is pressed
68
def pressed3(event):
print('Button-3 pressed at x = % d, y = % d'%(event.x, event.y))
## function to be called when button-1 is double clocked
defdouble_click(event):
print('Double clicked at x = % d, y = % d'%(event.x, event.y))
frame1 = Frame(root, height = 100, width = 200)
# Binding mouse buttons with the Frame widget
frame1.bind('<Button-2>', pressed2)
frame1.bind('<Button-3>', pressed3)
frame1.bind('<Double 1>', double_click)
frame1.pack()
root.mainloop()
Output:
69
3.8.2 Handling Key Press Event In Python
Example:
fromtkinter import *
fromtkinter.ttk import *
defkey_press(event):
key = event.char
root = Tk()
root.geometry('200x100')
mainloop()
Output:
71
QUESTIONS
6. Write the GUI program to create List Box for shopping cart.
10. Wrtite a Pyhton program to create check button for selecting multiple
hobbies.
72
SCHOOL OF COMPUTING
DBMS
To store data, a file or database can be used. A file stores data in the
secondary storage device like hard disk, either in the text format or binary
format.
1
operations, a database comes with software. This is called a database
management system.
SQL
NoSQL
4.1.1 MongoDB
Big Data
Content Management and Delivery
2
Mobile and Social Infrastructure
User Data Management
Data Hub
PyMongo
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-
32\Scripts>python -m pip install pymongo
Big Data
Content Management and Delivery
Mobile and Social Infrastructure
User Data Management
3
Data Hub
Test PyMongo
demo_mongodb_test.py:
import pymongo
Creating a Database
MongoDB will create the database if it does not exist, and make a connection to
it.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
4
MongoDB waits until you have created a collection (table), with at least one
document (record) before it actually creates the database (and collection).
Creating a Collection
To create a collection in MongoDB, use database object and specify the name
of the collection you want to create.
Program
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
5
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mylist = [
6
{ "name": "Amy", "address": "Apple st 652"},
{ "name": "Hannah", "address": "Mountain 21"},
{ "name": "Michael", "address": "Valley 345"},
{ "name": "Sandy", "address": "Ocean blvd 2"},
{ "name": "Betty", "address": "Green Grass 1"},
{ "name": "Richard", "address": "Sky st 331"},
{ "name": "Susan", "address": "One way 98"},
{ "name": "Vicky", "address": "Yellow Garden 2"},
{ "name": "Ben", "address": "Park Lane 38"},
{ "name": "William", "address": "Central st 954"},
{ "name": "Chuck", "address": "Main Road 989"},
{ "name": "Viola", "address": "Sideway 1633"}
]
x = mycol.insert_many(mylist)
Just like the SELECT statement is used to find data in a table in a MySQL
database.
Find One
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.find_one()
print(x)
Output
Find All
To select data from a table in MongoDB, we can also use the find() method.
The first parameter of the find() method is a query object. In this example we
use an empty query object, which selects all documents in the collection.
8
Example
Return all documents in the "customers" collection, and print each document:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mycol.find():
print(x)
9
Filter the Result
When finding documents in a collection, you can filter the result by using a
query object.
The first argument of the find() method is a query object, and is used to limit
the search.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
output
10
Example
Find documents where the address starts with the letter "S" or higher:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc = mycol.find(myquery)
for x in mydoc:
print(x)
Output
11
Return Only Some Fields
This parameter is optional, and if omitted, all fields will be included in the
result.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Output
Use the sort() method to sort the result in ascending or descending order.
The sort() method takes one parameter for "fieldname" and one parameter for
"direction" (ascending is the default direction).
Example
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mydoc =
mycol.find().sort("name")
13
for x in mydoc:
print(x)
OUTPUT
Sort Descending
sort("name", 1) #ascending
sort("name", -1) #descending
Example
14
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
for x in mydoc:
print(x)
Output
Note: If the query finds more than one document, only the first occurrence is
deleted.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.delete_one(myquery)
Example
Delete all documents were the address starts with the letter S:
16
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
x = mycol.delete_many(myquery)
output
2 documents deleted.
Delete All Documents in a Collection
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
17
x = mycol.delete_many({})
Output:
11 documents deleted
Delete Collection
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.drop()
The drop() method returns true if the collection was dropped successfully, and
false if the collection does not exist.
18
Python MongoDB Update
Note: If the query finds more than one record, only the first occurrence is
updated.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
mycol.update_one(myquery, newvalues)
19
for x in mycol.find():
print(x)
OUTPUT
Update Many
To update all documents that meets the criteria of the query, use
the update_many() method.
Example
Update all documents where the address starts with the letter "S":
import pymongo
20
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
Output
2 documents updated.
The limit() method takes one parameter, a number defining how many
documents to return.
Example
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myresult = mycol.find().limit(5)
OUTPUT
{'_id': 1, 'name': 'John', 'address': 'Highway37'}
{'_id': 2, 'name': 'Peter', 'address': 'Lowstreet 27'}
22
{'_id': 3, 'name': 'Amy', 'address': 'Apple st 652'}
{'_id': 4, 'name': 'Hannah', 'address': 'Mountain 21'}
{'_id': 5, 'name': 'Michael', 'address': 'Valley 345'}
import mysql.connector;
conn=mysql.connector.connect(host=’localhost’,database=’university’,user=’r
oot’, password=’***’)
The next step is to create cursor class object by calling the cursor() method on
‘conn’ object as:
cursor=con.cursor()
23
example: cursor.execute(“select * from emptab”)
The resultant rows retirieved from the table are stored in cursor object. the
result can be fetched using fetchone() or fetchall() methods.
Finally, the connection with MySQL can be closed by closing the cursor and
connection objects as:
cursor.close()
conn.close()
Program: A python program to retrieve and display all rows from the student
table:
import mysql.connector;
conn=mysql.connector.connect(host=’localhost’,database=’university’,user=’r
oot’, password=’***’)
cursor=con.cursor()
row = cursor.fetchone()
24
print(row)
row=cursor.fetchone()
cursor.close()
conn.close()
Output:
Built in Exceptions
Exception Description
Warning Used for non-fatal issues. Must subclass
25
StandardError.
Error
Base class for errors. Must subclass
StandardError.
InterfaceError Used for errors in the database module, not the
database itself. Must subclass Error.
DatabaseError Used for errors in the database. Must subclass
Error.
DataError Subclass of DatabaseError that refers to errors in
the data.
OperationalError Subclass of DatabaseError that refers to errors
such as the loss of a connection to the database.
These errors are generally outside of the control of
the Python scripter.
Exception Description
IntegrityError Subclass of DatabaseError for situations that
would damage the relational integrity, such as
uniqueness constraints or foreign keys.
InternalError Subclass of DatabaseError that refers to errors
internal to the database module, such as a cursor
no longer being active.
ProgrammingError Subclass of DatabaseError that refers to errors
such as a bad table name and other things that can
safely be blamed on you.
26
27