Header Ads

Header ADS

tkinter events and binding

        Binding keyboard and mouse event  in Tkinter .

In tkinter we create buttons ( using Button() widget ) for performing some kind of actions or calling a function ,but if you want to call any function just by pressing any keyboard button or using mouse motion or click so in this case tkinter have a awesome feature for you .

event :  

In tkinter  when we press on any button  like pressing keyboard Enter button or double click mouse left button or even pressing default Tkinter button widget  is called as an event .

callback:

  • A callback is the name of function that is to be run / executed in response of any event .
  • callback can be defined as a free standing function in our program or as a class member 

binding events ..

mouse binding .




In the above code i created a small root/ tkinter window , which has a label init .
the above code shows how you can bind root window as well as any widget in tkinter with a function .
for binding the widget and root window i use a predefined tkinter function bind(event,function).

bind() . bind function takes two argument event and function ,means which event i am binding with my widget and when the event occur on that  widget which function is called and if you look at the function definition i also pass a parameter event in it which means that i created that function for a event only you cannot bind a button using command attribute with the event function .

now move to the code , i bind root and a label to some mouse event first one is if i double click my left mouse button on my root window the function 1 is called and if i single click my mouse left button on the label the function 2 is called  and perform the actions which are coded in it .

Mouse events ..

<Button-1>  : left mouse button .
<Button-2> : middle mouse button .
<Button-3> : right mouse button .

<B1-Motion> : dragging the mouse cursor by pressing the left mouse button .

<Button Release-1> : left button released.
<Double Button-1> or <Double-1> : double click on button 1.
<Enter> : mouse pointer entered on the widget .
<Leave> : mouse pointer left the widget .

.. there are some basic mouse event of tkinter ..

Keyboard binding .

binding a keyboard event with a function is same like binding mouse but the change is in only the first argument of bind() function .

as you can see i bind the key '  a  ' to my root window and when i press key '  a  ' , then the function is called .
same like mouse event there is a variety of keyboard event present in tkinter .

keyboard events :

<FocusIn>  : keyboard focus moved to a widget .

<FocusOut> : keyboard focus moved to another widget .

<Return>  : Enter key is pressed .

<key> : any key of keyboard is pressed , like in example is used small a key 

these are some of the basic keyboard event present in tkinter ..


















No comments

Powered by Blogger.