Python Tkinter Events

In this Python Tkinter tutorial, we will learn about Python Tkinter Events where we will understand How to create events in Python Tkinter. We will also cover different examples related to events. And we will also cover these topics.

  • Python Tkinter events
  • Python Tkinter events and binds
  • Python Tkinter events list
  • Python Tkinter event widget
  • Python Tkinter event attributes
  • Python Tkinter event class
  • Python Tkinter event handler
  • Python Tkinter event_generate
  • Python Tkinter event loop
  • Python Tkinter event_listener
  • Python Tkinter event.keysym

Python Tkinter Events

In this section, we are learning about Events in Python Tkinter.

The event is the mouse operation by the user or we can say that the “handler” function is called with an event object. It can handle all the functions related to them.

Code:

In the following code, we create a button by giving the text = “On Clicking Quit”. By click on the button, they print the Python Guides, and the quit command also execute.

  • Button() is used to run the command
  • Button.focus() is used to get the focus on a particular event.
from tkinter import *

def task(event):
    print("PythonGuides") 

ws=Tk()
ws.geometry("200x200")

button=Button(ws,text="On Clicking Quit",command= ws.quit)

button.focus()
button.pack(expand=True)
button.bind('<Button-1>', task)

ws.mainloop()

Output:

After running the above code we can see the window is generated in which a button is placed. User clicks on the button after clicking they print the text Python guide and automatically quit. When an event occurs the allotted function call automatically.

Python Tkinter Event
EventOutput

Read: Python Tkinter Animation

Python Tkinter event and bind

In this section, we will learn about how to bind an event in Python Tkinter.

Allocate a function to an event is known as event binding. When an event occurs the allotted function call automatically.

The syntax of the bind() method

widget.bind(event,handler,add=None)

Code:

In the following code, we can create a widget in which an event can occur. We create a button on the widget, if a user clicks on the button a single time the text shows after clicking on the button “Hello“. If the user doubles click on the button the execution of the program stop.

from tkinter import *
def task(event):
    print("Hello") 
def quit(event):                           
    print("Double click  to stop") 
    import sys; sys.exit()

ws=Tk()
ws.title("Python guides")
ws.geometry("200x200") 

button = Button(ws, text='Press')
button.pack(pady=10)
button.bind('<Button-1>', task)
button.bind('<Double-1>', quit) 
button.mainloop()

ws.title() is used to given the title to the widget.

sys is a function that gives the name to the existing Python module

Output:

After running the above code we get the following output in which we can see the widget. In the widget, a button is placed after clicking on the button once they print Hello. after that clicking again twice they quit all the programs.

Python Tkinter Binding event
Event binding Output

Read: Python Tkinter Multiple Windows Tutorial

Python Tkinter event list

In this section, we will learn about the Python Tkinter event list.

The list is connected objects or items written in sequence.

Here is the list of some events:

  • Button– Button is used as an event handler when we click on the button the program execute
  • Configure– configure is used to change the property of a widget.
  • Focus– completely focus on a particular widget.
  • Destroy-Terminate the particular widget.
  • Motion– Even where the mouse move entire on the widget.

Code:

In the following code, we use labels, buttons where the label is used to describe the text, and buttons are used to handle the event.

  • def show_text(e) is used to define display the message.
  • ws.bind() is used to bind the method like moving of cursor, movement of the mouse, typing on a keyboard.
  • ws.mainloop() = Mainloop is infinite loop of application window.
from tkinter import *

ws= Tk()

ws.title("Python guides")
ws.geometry("700x350")

def Show_Text(e):
   label.config(text="Life is short/ Do what you love", font=('Helvetica 14 bold'))

label= Label(ws, text= "")
label.pack(pady= 50)

ws.bind('<Button-1>',Show_Text)
ws.mainloop()

Output:

READ:  Matplotlib xlim - Complete Guide

By running the above code we get the following output we see a widget is created. In starting there is no text on the widget when we move the cursor over the widget we get some text “life is short/Do what you love”.

Python Tkinter event list
EventlistOutput

Read: Python Tkinter Editor

Python Tkinter event widget

In this section, we will learn how we can create an event widget in Python Tkinter.

Before moving forward we should have a piece of knowledge about what is a widget?

Widget is component of the Graphical user interface which show the information from which user can interact with the operating system. The event occurs in the widget.

Code:

In the following code, the event.widget is used to create a widget. Adding a function to an event of a widget is called an event binding. When an event happens, the assigned function is invoked automatically.

  • def clickI(event): is used to display the message.
  • event.widget.config is working as a reference of passing an object to our function.
  • Lamba function is used to reduce the number of lines of codes.
from tkinter import *

def clickI(event):
    print ("you clicked on"), event.widget
    event.widget.config(text="Thank_You")


def clickII(event, Obj):
    print ("you clicked on"), Obj
    Obj.config(text="Thank_You!")

ws = Tk()
ws.geometry("200x200")
a1 = Label(ws, text="Press")
a2 = Label(ws, text="No, Press!")
a1.pack(pady=10)
a2.pack(pady=10)

a1.bind("<1>", clickI)
a2.bind("<1>", lambda event, obj=a2: clickII(event, obj))

ws.mainloop()

Output:

Here in this output, we can see we created a widget and binding two buttons that performing some action while clicking on it.

Python Tkinter Event widget 2
Event Widget Output

Read: Python Tkinter Table Tutorial

Python Tkinter event attributes

In this section, we are learning about Python Tkinter event attributes. Attributes are defined in an event class and received values from the event class. Attribute values can come by default as mentioned by the event class definition.

Code:

In the following code, we defined some functions that calling the attributes. Attributes are some kind of special characters, normal characters, and numbers. that we used to display text on the screen.

Here some event attributes used in this code are:

  • .char defining a normal character of an alphabet.
  • .height attribute is used to set the widget to a new height.
  • .keysym attribute is used to set keys in the string, numbers, special characters.
import tkinter
from tkinter import *

ws = Tk(  )
ws.geometry("200x200")
display='Press Any Button, or Press  Key'
Lab= Label(ws, text=display, width=len(display))
Lab.pack(pady=40)

def key(eve):
    if eve.char==eve.keysym:
        message ='Normal Key %r' % eve.char
    elif len(eve.char)==1:
        message ='Punctuation Key %r (%r)' % (eve.keysym, eve.char)
    else:
        message ='Special Key %r' % eve.keysym
    Lab.config(text=message)
Lab.bind_all('<Key>', key)

def do_mouse(eventname):
    def mouse_binding(event):
        message = 'Mouse event %s' % eventname
        Lab.config(text=message)
    Lab.bind_all('<%s>'%eventname, mouse_binding)

for i in range(1,4):
    do_mouse('Button-%s'%i)
    do_mouse('ButtonRelease-%s'%i)
    do_mouse('Double-Button-%s'%i)


ws.mainloop(  )

Output:

In the following output, we can see how attributes are working on the console as we use the mouse pointer attribute which shows a mouse event on a screen.

Here, it also works with keyboard buttons that show different attributes like characters, symbols, etc.

Python Tkinter event attribute
Event Attribute Output

Read: Python Tkinter Quiz

Python Tkinter event class

In this section, we will learn how we can create an event class in Python Tkinter.

Before learning the event class, we should have a piece of knowledge about the Class. Class is a code template that is used to create an object. To create a class we use the class keyword.

If the class is having no functionality then there is no use of a class. By functionality, we mean its attributes which act as a container for data and functions. The functions are known as methods.

READ:  PyTorch fully connected layer

Code:

In the following code, we create a class with the name of “myfirstapp” defining two objects in this, from which an object is calling another object and showing its value that is showing by clicking on a button.

  • def __init__(self,master) defines a class with objects.
  • Label() is like normal text given to widget.
from tkinter import Tk, Label, Button

class myfirstapp:
    def __init__(Self, master):
        Self.Master = master
        master.title("Python Guides")

        Self.lab = Label(master, text="This is my app")
        Self.lab.pack()

        Self.greet_button = Button(master, text="click here to Enter", command=Self.click_here_to_enter)
        Self.greet_button.pack()

        Self.close_button = Button(master, text="Exit", command=master.quit)
        Self.close_button.pack()

    def click_here_to_enter(self):
        print("Welcome")

ws = Tk()
ws.geometry("200x200")
My_app = myfirstapp(ws)
ws.mainloop()

Output:

After running the following code we get this output where we make a label and defines a button that helps to call an object and shows the value.

Python Tkinter eventclass1
Event Class Output

Read: Python QR code generator using pyqrcode in Tkinter

Python Tkinter event handler

In this section, we will learn about the event handler in Python Tkinter.

As the name show handler, it can describe handling something. An event handler is a part of events that is responsible for managing all callbacks that are executed and invoked. It is simply an action like clicking on a button that leads to another event.

Code:

In the following code, we define a class in which we created an object. We added an event handler on a button which is actions to quit a window. It Handles the input received in an event.

  • Self.master.title() is used to give the title to a window.
  • Button() is performing an event handler which performs an action of exit.
from tkinter import *

ws = Tk()

ws.geometry("200x200")

class Win(Frame):

    def __init__(self, master=None):
         
        Frame.__init__(self, master)   
              
        self.master = master

        self.init_win()

    def init_win(self):

        self.master.title("Python Guides")

        self.pack(fill=BOTH, expand=1)

        Exitbutton = Button(self, text="quit",command=self.Client_Quit)
        Exitbutton.place(x=0, y=0)
 
    def Client_Quit(self):
        exit()

pro = Win(ws)

ws.mainloop() 

Output:

From the following code, we get the input from a program that is performing an event handler. We can see an output of the following action.

Python Tkinter event handler
Event_handler Output

Read: How to Create a Snake Game in Python Tkinter

Python Tkinter event_generate

In this section, we will learn how we can generate an event by event_generate in Python Tkinter.

In simple words, we understand by word Generate is to bring something into existence. Even we also understand generate is used to produce or to create.

Here in this event_generate, we generated an event that shows some action and brings something into existence.event_generate is a default process that callback the event.

The syntax of the following:

widget.event_generate(sequence,when='tail')

Code:

In the following code, we create a widget in which time changed continuously.

event_geterate produce with when attribute when=’tail’. tail is to append it to the event queue after any events have been processed.

import threading
import time
import queue
from tkinter import *

ws = Tk()

ws.geometry("200x200")

comque= queue.Queue()

def timeThread():
    prestime = 0
    while 1:
        
        comque.put(prestime)
        
        try:
            ws.event_generate('<<TimeChanged>>', when='tail')
        
        except TclError:
            break
   
        time.sleep(1)
        prestime += 1


clcvar = IntVar()
Label(ws, textvariable=clcvar, width=9).pack(pady=10)


def timeChanged(event):
    clcvar.set(comque.get())

ws.bind('<<TimeChanged>>', timeChanged)


Thr=threading.Thread(target=timeThread)
Thr.start()

ws.mainloop()

Output:

In this following output, time is generated which continuously changes in seconds as we are seen in this.

Python tkinter event_generate
event_generate Output

Read: Python Tkinter Image

Python Tkinter event loop

In this section, we will learn how to create an event loop in python Tkinter.

Before learning about Python Tkinter even loop we should have a piece of knowledge about what is a loop.

Loop is a process where the end of which is connected to the beginning.

The event loop is an asynchronous process that converts tuple representing a time and returns to local time.

time.asctime()

Code:

In the following code, we create a widget in which local time is running in a loop.

  • time.asctime() converts a tuple representing a time as returned as the local time of 24 character string.
  • Frame() is used to display us as a simple rectangle. we use frame to organize other widgets to create a frame we use tkk.frame.
from tkinter import *
import time
from tkinter import ttk

def swap_Text():
    lab['text'] = time.asctime()

    ws.after(1000, swap_Text)

ws = Tk()
frame = ttk.Frame(ws)
frame.pack(fill='both', expand=True)

lab = ttk.Label(frame, text='0')
lab.pack()

swap_Text()      

ws.geometry('300x200')
ws.mainloop()

Output:

READ:  Scikit learn Genetic algorithm

In this following output, we see in output how asctime() is used which is converting a struct_time and returned as localtime() in 24 string characters as mentioned in output.

Python Tkinter event loop
Event Loop Output

Read: Python Tkinter Colors

Python Tkinter event_listener

In this section, we will learn about an event listener in Python Tkinter.

An event listener is a function that waits for an event to occur Like clicking on a mouse.

An event listener is used in two ways:

  • Call the listener with a new message.
  • By calling the method on_message_received.

Code:

In the following code, we create a widget and an event listener by setting predefined values which when we delete in the background it calls to the event listener.

  • event_listener.set() is used to set a Predefined value.
  • event_listener.trace() is used to modify the predefined value.
from tkinter import *

def modify(*args):
    print("Listning")

ws = Tk()
ws.geometry('200x200')
ws.title("Python Guides")

event_listener = StringVar()
event_listener.set("DELETE ME")
event_listener.trace("w", modify)

entry_widget = Entry(ws, textvariable = event_listener)
entry_widget.pack()

ws.mainloop()

Output:

In the following output, we can see in a gif we are deleting some values and adding ours as in another output we can see in the console a message listening is shown which indicates that our event listener is working over the background.

Python Tkinter event listner
event listener Output

Console indicates a message to show the running of event_listener().

python tkinter listener
Event Listener Output

Read: Python Tkinter Autocomplete

Python Tkinter event.keysym

In this section, we will learn about event.keysym in Python Tkinter.

Keysym attribute is used to set keys in the string for letters, numbers, and special characters like [a,b,c…….],[1,2,3,4……],[! @,#,%,^……]. Which is only used to describe keyboard events.

Code:

In the following code, we defined some functions that calling the attributes. Attributes are some kind of special characters, normal characters, and numbers. that we used to display text on the screen.

eve.keysym attribute is used to define the keyboard events.

import tkinter
from tkinter import *

ws = Tk(  )
ws.geometry("200x200")
display='Press Any Button, or Press  Key'
Lab= Label(ws, text=display, width=len(display))
Lab.pack(pady=40)

def key(eve):
    if eve.char==eve.keysym:
        message ='Normal Key %r' % eve.char
    elif len(eve.char)==1:
        message ='Punctuation Key %r (%r)' % (eve.keysym, eve.char)
    else:
        message ='Special Key %r' % eve.keysym
    Lab.config(text=message)
Lab.bind_all('<Key>', key)

def do_mouse(eventname):
    def mouse_binding(event):
        message = 'Mouse event %s' % eventname
        Lab.config(text=message)
    Lab.bind_all('<%s>'%eventname, mouse_binding)

for i in range(1,4):
    do_mouse('Button-%s'%i)
    do_mouse('ButtonRelease-%s'%i)
    do_mouse('Double-Button-%s'%i)


ws.mainloop()

Output:

In the following output, we can see the function of the .event_keysym attribute which is describing keyboard events as when a user presses any key or uses a mouse everything will be seen to a console as seen in the below gif.

Python tkinter event.keysym
event.keysym Output

In this tutorial, we discuss Python Tkinter Event and we have also covered different examples related to its implementation. Here is the list of topics that we have covered.

  • Python Tkinter events
  • Python Tkinter events and bindings
  • Python Tkinter events list
  • Python Tkinter event widget
  • Python Tkinter event attributes
  • Python Tkinter event class
  • Python Tkinter event handler
  • Python Tkinter event_generate
  • Python Tkinter event loop
  • Python Tkinter event_listener
  • Python Tkinter event.keysym

Related Posts: