An event is said to occur whenever a user presses a certain key, drags something on a canvas, uses the mouse wheel, etc. A Tkinter application runs most of its time inside an event loop, which is entered via the mainloop method. It waits for the events to occur.
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)
Whenever the defined event occurs in the widget, the "handler" function is called with an event object. describing the event.
Tkinter uses the event sequences which allows the user to define what events should be bind to the handlers. This 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 mandatory 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. Following list shows some common events:
It's time to use some of the events in programs to have a better understanding how they work. See the following program:
from tkinter import *
def hello(event):
print("Single Click, Button-l")
def leftk(event):
print("The left mouse button is released, ButtonRelease-1")
def rightk(event):
print("The right mouse button is released, ButtonRelease-3")
def mouse(event):
print("The mouse is moved, Motion")
def mw(event):
print("The mouse wheel is moved, MouseWheel")
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('<ButtonRelease-3>', leftk)
widget.bind('<Motion>', mouse)
widget.bind('<MouseWheel>', mw)
widget.bind('<Double-1>', quit)
widget.mainloop()
The output of the program is shown below:
In the command window we can see the what events occurred when we used a mouse.
The most useful attributes in the Event object are:
The output of the program is shown below:
The following program prints out the names of the keys that were pressed:
from tkinter import *
def callback(event):
print(event.keysym)
root = Tk()
root.bind('<Key>', callback)
mainloop()
The output of the program is shown below:
We can use these name in the if-elif statements as shown in the following program which is a modification of our square root calculator program:
from tkinter import *
import math
def callback(event):
def calculate():
num = int(entry.get())
squareroot = math.sqrt(num)
output_label.configure(text = 'Square root: {:.1f}'.format(squareroot))
entry.delete(0,END)
if event.keysym == 'y':
print("You wish to continue")
message_label = Label(text = 'Enter a number',font =('Verdana',16))
output_label = Label(font=('Verdana', 16))
entry = Entry(font =('Verdana',16),width =4)
entry.bind('<Return>', lambda dummy=0:calculate())
message_label.grid(row=0,column=0)
entry.grid(row=0,column=1)
output_label.grid(row=1,column=0,columnspan=3)
elif event.keysym =='n':
print("You do not wish to continue")
import sys; sys.exit()
root = Tk()
print("This program calculates Square root\n")
print("Press 'y' if you wish to continue and 'n' if you do not wish to continue\n")
root.bind('<Key>', callback)
mainloop()
The output of the program is shown below:
If we enter 'y' as our choice then the output changes to:
Enter the number whose square root is to be calculated :
After pressing enter:
If the selection was 'n' the program ends :
This is just an example to demonstrate use of keysym attribute and there is always scope for improvement. Using this program we can also find the names of all the keys.
A few common keys are:
<Return> Enter key
<Tab> Tab key
<Space> Spacebar
<F1>, . . . , <F12> F1, . . . , F12
<Next>, <Prior> Page up, Page down
<Up>, <Down>, <Left>, <Right> Arrow keys
<Home>, <End> Home, End
<Insert>, <Delete> Insert, Delete
<Caps_Lock>, <Num_Lock> Caps lock, Number lock
<Control_L>, <Control_R> Left and right Control keys
<Alt_L>, <Alt_R> Left and right Alt keys
<Shift_L>, <Shift_R> Left and right Shift keys
Most printable keys can be captured with their names as shown in the following program:
from tkinter import *
def callback(event):
print(event.keysym)
root = Tk()
root.bind('a', callback)
root.bind('A', callback)
root.bind('-', callback)
mainloop()
root.bind('a', callback)
root.bind('A', callback)
root.bind('-', callback)
The output of the program is shown below:
The exceptions are the spacebar (<Space>) and the less than sign (<Less>). You can also catch key
combinations, such as <Shift-F5>, <Control-Next>, <Alt-2>, or <Control-Shift-F1>.
So far we always bind keypresses to root, which is our name for the main window. We can also bind key presses to specific widgets. For instance, if you only want the left arrow key to work on a Canvas called canvas, you could use the following:
canvas.bind(<Left>, callback)
Using the following program example a user can move a rectangle with the left or right arrow keys:
from tkinter import *
def callback(event):
global move
if event.keysym=='Right':
move += 1
elif event.keysym=='Left':
move -=1
canvas.coords(rect,50+move,50,100+move,100)
root = Tk()
root.bind('<Key>', callback)
canvas = Canvas(width=200,height=200)
canvas.grid(row=0,column=0)
rect = canvas.create_rectangle(50,50,100,100,fill='red')
move = 0
mainloop()
The output of the program is shown below:
See the initial position of the rectangle and after using right arrow key we moved the rectangle towards right side.
Here I am ending today's post. See you again with a new topic, till then keep practicing and learning Python as Python is easy to learn!
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)
Whenever the defined event occurs in the widget, the "handler" function is called with an event object. describing the event.
Tkinter uses the event sequences which allows the user to define what events should be bind to the handlers. This 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 mandatory 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. Following list shows some common events:
- <Button-1> - The left mouse button is clicked.
- <Double-Button-1> - The left mouse button is double-clicked.
- <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
- <B1-Motion> - A click-and-drag with the left mouse button.
- <MouseWheel> - The mouse wheel is moved.
- <Motion> - The mouse is moved.
- <Enter> - The mouse is now over the widget.
- <Leave> - The mouse has now left the widget.
- <Key> - A key is pressed.
- <key name> - The key name key is pressed.
- <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.
- 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.
It's time to use some of the events in programs to have a better understanding how they work. See the following program:
from tkinter import *
def hello(event):
print("Single Click, Button-l")
def leftk(event):
print("The left mouse button is released, ButtonRelease-1")
def rightk(event):
print("The right mouse button is released, ButtonRelease-3")
def mouse(event):
print("The mouse is moved, Motion")
def mw(event):
print("The mouse wheel is moved, MouseWheel")
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('<ButtonRelease-3>', leftk)
widget.bind('<Motion>', mouse)
widget.bind('<MouseWheel>', mw)
widget.bind('<Double-1>', quit)
widget.mainloop()
The output of the program is shown below:
In the command window we can see the what events occurred when we used a mouse.
The most useful attributes in the Event object are:
- keysym - The name of the key that was pressed
- x, y - The coordinates of the mouse pointer
- delta - The value of the mouse wheel
The following program catches key presses as shown below:
from tkinter import *
def callback1(event):
print('You pressed the enter key.')
def callback2(event):
print('You pressed the up arrow.')
root = Tk()
root.bind('<Return>', callback1)
root.bind('<Up>', callback2)
mainloop()
The output of the program is shown below:
The following program prints out the names of the keys that were pressed:
from tkinter import *
def callback(event):
print(event.keysym)
root = Tk()
root.bind('<Key>', callback)
mainloop()
The output of the program is shown below:
We can use these name in the if-elif statements as shown in the following program which is a modification of our square root calculator program:
from tkinter import *
import math
def callback(event):
def calculate():
num = int(entry.get())
squareroot = math.sqrt(num)
output_label.configure(text = 'Square root: {:.1f}'.format(squareroot))
entry.delete(0,END)
if event.keysym == 'y':
print("You wish to continue")
message_label = Label(text = 'Enter a number',font =('Verdana',16))
output_label = Label(font=('Verdana', 16))
entry = Entry(font =('Verdana',16),width =4)
entry.bind('<Return>', lambda dummy=0:calculate())
message_label.grid(row=0,column=0)
entry.grid(row=0,column=1)
output_label.grid(row=1,column=0,columnspan=3)
elif event.keysym =='n':
print("You do not wish to continue")
import sys; sys.exit()
root = Tk()
print("This program calculates Square root\n")
print("Press 'y' if you wish to continue and 'n' if you do not wish to continue\n")
root.bind('<Key>', callback)
mainloop()
The output of the program is shown below:
If we enter 'y' as our choice then the output changes to:
Enter the number whose square root is to be calculated :
After pressing enter:
If the selection was 'n' the program ends :
This is just an example to demonstrate use of keysym attribute and there is always scope for improvement. Using this program we can also find the names of all the keys.
A few common keys are:
<Return> Enter key
<Tab> Tab key
<Space> Spacebar
<F1>, . . . , <F12> F1, . . . , F12
<Next>, <Prior> Page up, Page down
<Up>, <Down>, <Left>, <Right> Arrow keys
<Home>, <End> Home, End
<Insert>, <Delete> Insert, Delete
<Caps_Lock>, <Num_Lock> Caps lock, Number lock
<Control_L>, <Control_R> Left and right Control keys
<Alt_L>, <Alt_R> Left and right Alt keys
<Shift_L>, <Shift_R> Left and right Shift keys
Most printable keys can be captured with their names as shown in the following program:
from tkinter import *
def callback(event):
print(event.keysym)
root = Tk()
root.bind('a', callback)
root.bind('A', callback)
root.bind('-', callback)
mainloop()
root.bind('a', callback)
root.bind('A', callback)
root.bind('-', callback)
The output of the program is shown below:
The exceptions are the spacebar (<Space>) and the less than sign (<Less>). You can also catch key
combinations, such as <Shift-F5>, <Control-Next>, <Alt-2>, or <Control-Shift-F1>.
So far we always bind keypresses to root, which is our name for the main window. We can also bind key presses to specific widgets. For instance, if you only want the left arrow key to work on a Canvas called canvas, you could use the following:
canvas.bind(<Left>, callback)
Using the following program example a user can move a rectangle with the left or right arrow keys:
from tkinter import *
def callback(event):
global move
if event.keysym=='Right':
move += 1
elif event.keysym=='Left':
move -=1
canvas.coords(rect,50+move,50,100+move,100)
root = Tk()
root.bind('<Key>', callback)
canvas = Canvas(width=200,height=200)
canvas.grid(row=0,column=0)
rect = canvas.create_rectangle(50,50,100,100,fill='red')
move = 0
mainloop()
The output of the program is shown below:
See the initial position of the rectangle and after using right arrow key we moved the rectangle towards right side.
Here I am ending today's post. See you again with a new topic, till then keep practicing and learning Python as Python is easy to learn!
0 comments:
Post a Comment