Binding function in Python Tkinter

PythonServer Side ProgrammingProgramming

In python tkinter is a GUI library that can be used for various GUI programming. Such applications are useful to build desktop applications. In this article we will see one aspect of the GUI programming called Binding functions. This is about binding events to functions and methods so that when the event occurs that specific function is executed.

Binding keyboard event

In the below example we bind the press of any key from the keyboard with a function that gets executed. Once the Tkinter GUI window is open, we can press any key in the keyboard and we get a message that the keyboard is pressed.

Example

from tkinter import *

# Press a buton in keyboard
def PressAnyKey(label):
   value = label.char
   print(value, ' A button is pressed')

base = Tk()
base.geometry('300x150')
base.bind('<Key>', lambda i : PressAnyKey(i))
mainloop()

Output

Running the above code gives us the following result −

Binding Mouse click events

In the below example we see how to bind the mouse click events on a tkinter window to a function call. In the below example we call the events to display the left-button double click, right button click and scroll-button click to display the position in the tkinter canvas where the buttons were clicked.

Example

from tkinter import *
from tkinter.ttk import *

# creates tkinter window or root window
base = Tk()
base.geometry('300x150')

# Press the scroll button in the mouse then function will be called
def scroll(label):
   print('Scroll button clicked at x = % d, y = % d'%(label.x, label.y))
# Press the right button in the mouse then function will be called
def right_click(label):
   print('right button clicked at x = % d, y = % d'%(label.x, label.y))
# Press the left button twice in the mouse then function will be called
def left_click(label):
   print('Double clicked left button at x = % d, y = % d'%(label.x, label.y))

Function = Frame(base, height = 100, width = 200)
Function.bind('<Button-2>', scroll)
Function.bind('<Button-3>', right_click)
Function.bind('<Double 1>', left_click)
Function.pack()
mainloop()

Output

Running the above code gives us the following result −

raja
Published on 10-Jul-2020 09:46:21
Advertisements