[go: up one dir, main page]

0% found this document useful (0 votes)
19 views28 pages

Chapter 5

Python Chapter 5

Uploaded by

bidaatmaslake
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views28 pages

Chapter 5

Python Chapter 5

Uploaded by

bidaatmaslake
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

CHAPTER -5

FILE I/O & EXCEPTION HANDLING

5.1 The file Object Attributes


Opening and Closing Files
Python provides basic functions and methods necessary to manipulate files by default.
You can do most of the file manipulation using a file object.

The open Function


Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to call other
support methods associated with it.

Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
• file_name − The file_name argument is a string value that contains the name of
the file that you want to access.
• access_mode − The access_mode determines the mode in which the file has to
be opened, i.e., read, write, append, etc. A complete list of possible values is
given below in the table. This is optional parameter and the default file access
mode is read (r).
• buffering − If the buffering value is set to 0, no buffering takes place. If the
buffering value is 1, line buffering is performed while accessing a file. If you
specify the buffering value as an integer greater than 1, then buffering action is
performed with the indicated buffer size. If negative, the buffer size is the system
default(default behavior).
Here is a list of the different modes of opening a file −

Sr.No. Modes & Description


1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.

2 rb
Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file.

3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.

4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.

5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.

6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.

7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists.
If the file does not exist, creates a new file for reading and writing.

8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for reading and
writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file
for writing.

10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the file does not exist, it
creates a new file for writing.

11 a+
Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.

12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at
the end of the file if the file exists. The file opens in the append mode. If the file
does not exist, it creates a new file for reading and writing.

Once a file is opened and you have one file object, you can get various information
related to that file.
Here is a list of all attributes related to file object −

Sr.No. Attribute & Description

1 file.closed
Returns true if file is closed, false otherwise.

2 file.mode
Returns access mode with which file was opened.

3 file.name
Returns name of the file.
4 file.softspace
Returns false if space explicitly required with print, true otherwise.

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace

This produces the following result −


Name of the file: foo.txt
Closed or not : False
Opening mode : wb
Softspace flag : 0

The close() Method


The close() method of a file object flushes any unwritten information and closes the file
object, after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.

Syntax
fileObject.close()

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name

# Close opend file


fo.close()

This produces the following result −


Name of the file: foo.txt

5.2 Reading and Writing Files


The file object provides a set of access methods to make our lives easier. We would see
how to use read() and write() methods to read and write files.

The write() Method


The write() method writes any string to an open file. It is important to note that Python
strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −

Syntax
fileObject.write(string)
Here, passed parameter is the content to be written into the opened file.

Example
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n")

# Close opend file


fo.close()

The above method would create foo.txt file and would write given content in that file and
finally it would close that file. If you would open this file, it would have following content.
Python is a great language.
Yeah its great!!

The read() Method


The read() method reads a string from an open file. It is important to note that Python
strings can have binary data. apart from text data.

Syntax
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if count is missing, then it tries
to read as much as possible, maybe until the end of file.

Example
Let's take a file foo.txt, which we created above.
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()

This produces the following result −


Read String is : Python is

File Positions
The tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference
position from where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1
means use the current position as the reference position and if it is set to 2 then the end
of the file would be taken as the reference position.

Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python

# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print "Read String is : ", str

# Check current position


position = fo.tell()
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10)
print "Again read String is : ", str
# Close opend file
fo.close()

This produces the following result −


Read String is : Python is
Current file position : 10
Again read String is : Python is

5.3 Renaming and Deleting Files


Python os module provides methods that help you perform file-processing operations,
such as renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.

The rename() Method


The rename() method takes two arguments, the current filename and the new filename.

Syntax
os.rename(current_file_name, new_file_name)

Example
Following is the example to rename an existing file test1.txt −
#!/usr/bin/python
import os

# Rename a file from test1.txt to test2.txt


os.rename( "test1.txt", "test2.txt" )

The remove() Method


You can use the remove() method to delete files by supplying the name of the file to be
deleted as the argument.

Syntax
os.remove(file_name)
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os

# Delete file test2.txt


os.remove("text2.txt")

Exception Handling: -
What is Exception?

An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions. In general, when a Python script
encounters a situation that it cannot cope with, it raises an exception. An exception is a
Python object that represents an error.
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

5.4 Handling an exception


If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include
an except: statement, followed by a block of code which handles the problem as
elegantly as possible.

Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Here are few important points about the above-mentioned syntax −
• A single try statement can have multiple except statements. This is useful when
the try block contains statements that may throw different types of exceptions.
• You can also provide a generic except clause, which handles any exception.
• After the except clause(s), you can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
• The else-block is a good place for code that does not need the try: block's
protection.

Example
This example opens a file, writes content in the, file and comes out gracefully because
there is no problem at all −
#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()

This produces the following result −


Written content in the file successfully

Example
This example tries to open a file where you do not have write permission, so it raises an
exception −
#!/usr/bin/python

try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"

This produces the following result −


Error: can't find file or read data
The except Clause with No Exceptions
You can also use the except statement with no exceptions defined as follows −
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.
This kind of a try-except statement catches all the exceptions that occur. Using this kind
of try-except statement is not considered a good programming practice though, because
it catches all exceptions but does not make the programmer identify the root cause of
the problem that may occur.

The except Clause with Multiple Exceptions


You can also use the same except statement to handle multiple exceptions as follows −
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.

The try-finally Clause


You can use a finally: block along with a try: block. The finally block is a place to put
any code that must execute, whether the try-block raised an exception or not. The syntax
of the try-finally statement is this −
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

You cannot use else clause as well along with a finally clause.
Example
#!/usr/bin/python

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"

If you do not have permission to open the file in writing mode, then this will produce the
following result −
Error: can't find file or read data
Same example can be written more cleanly as follows −
#!/usr/bin/python

try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"

When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the exception
is raised again and is handled in the except statements if present in the next higher layer
of the try-except statement.

Argument of an Exception
An exception can have an argument, which is a value that gives additional information
about the problem. The contents of the argument vary by exception. You capture an
exception's argument by supplying a variable in the except clause as follows −
try:
You do your operations here;
......................
except ExceptionType, Argument:
You can print value of Argument here...

If you write the code to handle a single exception, you can have a variable follow the
name of the exception in the except statement. If you are trapping multiple exceptions,
you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause of the
exception. The variable can receive a single value or multiple values in the form of a
tuple. This tuple usually contains the error string, the error number, and an error location.

Example
Following is an example for a single exception −
#!/usr/bin/python

# Define a function here.


def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers\n", Argument

# Call above function here.


temp_convert("xyz");

This produces the following result −


The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'

Raising an Exceptions
You can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows.

Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a
value for the exception argument. The argument is optional; if not supplied, the exception
argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if
present, is the traceback object used for the exception.

Example
An exception can be a string, a class or an object. Most of the exceptions that the Python
core raises are classes, with an argument that is an instance of the class. Defining new
exceptions is quite easy and can be done as follows −
def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

Note: In order to catch an exception, an "except" clause must refer to the same
exception thrown either class object or simple string. For example, to capture above
exception, we must write the except clause as follows −
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...

Python provides two very important features to handle any unexpected error in your
Python programs and to add debugging capabilities in them −
• Exception Handling
• Assertions
5.5 Built in Exception: -

Sr.No. Exception Name & Description

1 Exception
Base class for all exceptions

2 StopIteration
Raised when the next() method of an iterator does not point to any object.

3 SystemExit
Raised by the sys.exit() function.

4 StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.

5 ArithmeticError
Base class for all errors that occur for numeric calculation.

6 OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.

7 FloatingPointError
Raised when a floating point calculation fails.

8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.

9 AssertionError
Raised in case of failure of the Assert statement.

10 AttributeError
Raised in case of failure of attribute reference or assignment.

11 EOFError
Raised when there is no input from either the raw_input() or input() function and
the end of file is reached.

12 ImportError
Raised when an import statement fails.

13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.

14 LookupError
Base class for all lookup errors.

15 IndexError
Raised when an index is not found in a sequence.

16 KeyError
Raised when the specified key is not found in the dictionary.

17 NameError
Raised when an identifier is not found in the local or global namespace.

18 UnboundLocalError
Raised when trying to access a local variable in a function or method but no value
has been assigned to it.

19 EnvironmentError
Base class for all exceptions that occur outside the Python environment.

20 IOError
Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist.

21 IOError
Raised for operating system-related errors.

22 SyntaxError
Raised when there is an error in Python syntax.

23 IndentationError
Raised when indentation is not specified properly.

24 SystemError
Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.
25 SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.

26 TypeError
Raised when an operation or function is attempted that is invalid for the specified
data type.

27 ValueError
Raised when the built-in function for a data type has the valid type of arguments,
but the arguments have invalid values specified.

28 RuntimeError
Raised when a generated error does not fall into any category.

29 NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited
class is not actually implemented.

5.6 User-Defined Exceptions


Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed
from RuntimeError. This is useful when you need to display more specific information
when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The
variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg

So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args

5.7 INTRODUCTION TO PYTHON GUI PROGRAMMING: -

Python provides various options for developing graphical user interfaces (GUIs). Most
important are listed below.
• Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
We would look this option in this chapter.
• wxPython − This is an open-source Python interface for
wxWindows http://wxpython.org.
• JPython − JPython is a Python port for Java which gives Python scripts seamless
access to Java class libraries on the local machine http://www.jython.org.
There are many other interfaces available, which you can find them on the net.

Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform
the following steps −
• Import the Tkinter module.
• Create the GUI application main window.
• Add one or more of the above-mentioned widgets to the GUI application.
• Enter the main event loop to take action against each event triggered by the user.

Example
from tkinter import *

#creating the application main window.

top = Tk()

#Entering the event main loop

top.mainloop()
This would create a following window −
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets.
There are currently 15 types of widgets in Tkinter. We present these widgets as well as
a brief description in the following table −

Sr.No. Operator & Description

1 Button

The Button widget is used to display buttons in your application.

2 Canvas

The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.

3 Checkbutton

The Checkbutton widget is used to display a number of options as checkboxes.


The user can select multiple options at a time.

4 Entry

The Entry widget is used to display a single-line text field for accepting values from
a user.

5 Frame
The Frame widget is used as a container widget to organize other widgets.

6 Label

The Label widget is used to provide a single-line caption for other widgets. It can
also contain images.

7 Listbox

The Listbox widget is used to provide a list of options to a user.

8 Menubutton

The Menubutton widget is used to display menus in your application.

9 Menu

The Menu widget is used to provide various commands to a user. These commands
are contained inside Menubutton.

10 Message

The Message widget is used to display multiline text fields for accepting values from
a user.

11 Radiobutton

The Radiobutton widget is used to display a number of options as radio buttons.


The user can select only one option at a time.

12 Scale

The Scale widget is used to provide a slider widget.

13 Scrollbar

The Scrollbar widget is used to add scrolling capability to various widgets, such as
list boxes.

14 Text

The Text widget is used to display text in multiple lines.

15 Toplevel
The Toplevel widget is used to provide a separate window container.

16 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.

17 PanedWindow

A PanedWindow is a container widget that may contain any number of panes,


arranged horizontally or vertically.

18 LabelFrame

A labelframe is a simple container widget. Its primary purpose is to act as a spacer


or container for complex window layouts.

19 tkMessageBox

This module is used to display message boxes in your applications.

Let us study these widgets in detail −

Standard attributes
Let us take a look at how some of their common attributes.such as sizes, colors and
fonts are specified.
• Dimensions
• Colors
• Fonts
• Anchors
• Relief styles
• Bitmaps
• Cursors
Let us study them briefly −

Geometry Management
All Tkinter widgets have access to specific geometry management methods, which have
the purpose of organizing widgets throughout the parent widget area. Tkinter exposes
the following geometry manager classes: pack, grid, and place.
• The pack() Method − This geometry manager organizes widgets in blocks before
placing them in the parent widget.
• The grid() Method − This geometry manager organizes widgets in a table-like
structure in the parent widget.
• The place() Method − This geometry manager organizes widgets by placing them
in a specific position in the parent widget.
Let us study the geometry management methods briefly −

Introduction to the Tkinter event binding


Assigning a function to an event of a widget is called event binding. When the event
occurs, the assigned function is invoked automatically.

bind a function to an event of a widget via the command option. However, not all Tkinter
widgets support the command option.

Therefore, Tkinter provides you with an alternative way for event binding via
the bind() method.

The following shows the general syntax of the bind() method:

widget.bind(event, handler, add=None)

When an event occurs in the widget, Tkinter will invoke the handler automatically with the
event detail.

If you want to register an additional handler, you can pass the '+' to the add argument. It
means that you can have multiple event handlers that respond to the same event.

Tkinter event binding examples


The following program illustrates how to bind the return_pressed function to the Return key
pressed event of the 'Save' button:

import tkinter as tk
from tkinter import ttk
def return_pressed(event):
print('Return key pressed.')

root = tk.Tk()

btn = ttk.Button(root, text='Save')


btn.bind('<Return>', return_pressed)

btn.focus()
btn.pack(expand=True)

root.mainloop()
Code language: Python (python)

In this example, the following statement calls the bind() method on the button widget to
bind the Return key pressed event:

btn.bind('<Return>', return_pressed)
Code language: HTML, XML (xml)

The following example illustrates how to use the bind() method to register multiple
handlers for the same event:

import tkinter as tk
from tkinter import ttk

def return_pressed(event):
print('Return key pressed.')

def log(event):
print(event)

root = tk.Tk()

btn = ttk.Button(root, text='Save')


btn.bind('<Return>', return_pressed)
btn.bind('<Return>', log, add='+')

btn.focus()
btn.pack(expand=True)
root.mainloop()
Code language: Python (python)

When you move the focus to the button and press the Return key, Tkinter automatically
invokes the return_pressed and log functions.

The following binds the log() function to the Return key pressed event of the 'Save' button:

btn.bind('<Return>', log, add='+')


Code language: Python (python)

In this statement, the third argument add='+' registered additional handler, which is
the log() function.

If you don’t specify the add='+' argument, the bind() method will replace the existing
handler (return_pressed) by the new one (log).

Binding events to root window


So far, you have learned how to bind an event to a particular widget. Tkinter also allows
you to bind an event to the top-level window.

In this case, the syntax for the bind() is the same except that you can call it on the root
window like this:

root.bind('<Return>', handler)
Code language: HTML, XML (xml)

The levels of binding


In the previous example, you have learned how to bind an event to a particular instance
of a widget. This is called an instance-level binding.

Tkinter also allows you to bind an event to all the instances of a widget. For example,
you can bind the event to all the textboxes in a program:

root.bind_class('Entry', '<Control-V>', paste)


Code language: JavaScript (javascript)

By the way, you use the Entry widget to create a textbox in Tkinter.
This is called class-level binding because you bind the event to a class instead of an
instance.

Unbinding events
Sometimes, you may want to undo the effect of an earlier binding. To do it, you can use
the unbind() method:

widget.unbind(event)
Code language: CSS (css)

The following example unbinds the event from the btn button:

btn.unbind('<Return>')
Code language: HTML, XML (xml)

Summary
• Use the bind() method to bind an event to a widget.
• Tkinter supports both instance-level and class-level bindings.

Events and Binds

Introduction

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.
#!/usr/bin/python3
# write tkinter as Tkinter to be Python 2.x compatible
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 impo
rtant that 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.

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 clicked instead of
Button> 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.

You might also like