Binding function in Tkinter Python

In this tutorial, we will learn about the Binding function in Tkinter Python.

Tkinter is a GUI(graphical user interface) package that is widely used for desktop applications. It is a standard GUI for python. It is used to make windows, buttons, text, images, and other things.

An event can be a key press or a mouse operation by the user. For each widget, it helps us to bind Python’s functions and methods to an event.

widget.bind(event, handler)

Check: Bind a function to a Tkinter button – Python GUI

Binding Mouse Click

In the below code, we bind the event of pressing the mouse button to change the color of the window to the root. So whenever we click the mouse button, the window color changes.

from random import choice
import tkinter as tk
root = tk.Tk()
currentColor = ""
colors = ['red','yellow','green','blue','black']
def colorChanger(event):
  if currentColor != "":
    currentColor = choice(colors)
    currentColor = choice(colors)
  root['bg'] = ch
label = tk.Label(root, text="Click where you want to change color")
root.bind("", colorChanger)

Binding Mouse Movement

The below code binds the output frame with the functions enterFrame and exitFrame. These functions print the position where mouse has entered and exited the frame.

from tkinter import * 

root = Tk() 

def enterFrame(event): 
    print('Entered the frame at x = % d, y = % d'%(event.x, event.y)) 

def exitFrame(event): 
    print('Exited the frame at x = % d, y = % d'%(event.x, event.y)) 

frame = Frame(root, height = 200, width = 300) 

frame.bind('<Enter>', enterFrame) 
frame.bind('<Leave>', exitFrame) 


Binding Keyboard Interaction

The below code binds the keyboard key press with the keyCount function and displays the number of keys pressed.

import tkinter as tk
keysPressed = 0
def keyCount():
    keysPressed += 1
    print("Pressed a key:", keysPressed ,"times")
root = tk.Tk()
root.bind("<Key>", lambda x: keyCount())
label = tk.Label(root, text="Press any number of keys and see the number of keys presses in the console")


Also read: Detect keypress in Tkinter in Python

Leave a Reply

Your email address will not be published. Required fields are marked *