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()
root.title("ColorChanger")
root.geometry("400x400+200+200")
currentColor = ""
colors = ['red','yellow','green','blue','black']
def colorChanger(event):
  if currentColor != "":
    colors.pop(colors.index(currentColor))
                colors.append(currentColor)
    currentColor = choice(colors)
  else:
    currentColor = choice(colors)
  root['bg'] = ch
 
label = tk.Label(root, text="Click where you want to change color")
label.pack(fill=tk.BOTH)
 
root.bind("", colorChanger)
root.mainloop()

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() 
root.title("Root")
root.geometry('300x200') 

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) 
  
frame.pack() 
root.mainloop()

 

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")
label.pack()
root.mainloop()

 

Also read: Detect keypress in Tkinter in Python

Leave a Reply

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