Events in Python

Manav Narula Jan 30, 2023
  1. Use the tkinter Module to Create GUI Applications in Python
  2. the Main Classes in Event Handling Using Python
  3. Use the pynput.keyboard Module to Detect Key Pressed in Python
Events in Python

Event handling creates a responsive application that can detect and generate actions on response.

An event is a response or action detected by an object. In Python, event handling is done using classes.

Use the tkinter Module to Create GUI Applications in Python

The tkinter module is used to create GUI applications, which wait for a response from the user and perform functions in a graphical interface.

the Main Classes in Event Handling Using Python

  • The publisher class generates an event.
  • The subscriber class receives these events.
class sample_event(object):
    def __init__(self):
        self.__eventhandler_sample = []

    def __iadd__(self, Eventhandler):
        self.__eventhandler_sample.append(Eventhandler)
        return self

    def __isub__(self, Eventhandler):
        self.__eventhandler_sample.remove(Eventhandler)
        return self

    def __call__(self, *args, **keywargs):
        for eventhandler_sample in self.__eventhandler_sample:
            eventhandler_sample(*args, **keywargs)


class MessToDisplay(object):
    def __init__(self, val):
        self.val = val

    def PrintM(self):
        print("Message for an event with value ", self.val)


class sample_class(object):
    def __init__(self):
        self.ob = sample_event()

    def EHnew(self):
        self.ob()

    def anotherevent(self, objMeth):
        self.ob += objMeth


def seq():
    newsample = sample_class()
    displayamess = MessToDisplay(5)
    newsample.anotherevent(displayamess.PrintM)
    newsample.EHnew()


seq()

Output:

Message for an event with value 5

The seq() function defines the flow of different events to print out a message, append it, and remove it.

There are different types of events in Python. Such as detecting keypress, cursor movement, mouse-click, and even timer-based events.

Use the pynput.keyboard Module to Detect Key Pressed in Python

from pynput.keyboard import Key, Listener


def press_key(k):
    print(k)


def release_key(k):
    if k == Key.space:
        return False


with Listener(on_press=press_key, on_release=release_key) as listener:
    listener.join()

Output:

'b'
Key.space

The Listener() function detects these events by executing the press_key and release_key functions

The spacebar needs to be pressed to stop the flow of these events as it returns false and will stop the Listener() function.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - Python Event