Python Event Handling

Here you will learn about GUI event handling in python, or event driven programming with python.

Binding Widgets and Event Handlers

As you have already learned about gui development using python, but haven't written some code to handle event. Therefore let's bind widgets with some events.

Python Event Handling Program

Here is a simple event handling program in python.

from tkinter import *;
class MyApp(Frame):
    def __init__(self, master):
        Frame.__init__(self, master);
        # below is the number of button clicks
        self.button_clicks = 0;
    def create_widget(self):
        self.buttn = Button(self, text = "Total Clicks = 0");
        self.buttn["command"] = self.update_click_count;
    def update_click_count(self):
        self.button_clicks += 1;
        self.buttn["text"] = "Total Clicks = " + str(self.button_clicks);
mainWindow = Tk();
mainWindow.title("GUI Event Handler");
app = MyApp(mainWindow);

Above event handling program counts the total mouse clicks by user. That is, initially it will be displayed as Total Clicks = 0 and when user click on that button, then it is update to Total Clicks = 1 and when again click on the same button, it will again update with incrementing the previous value (that is 1) by 1, and will become Total Clicks = 2 and so on.

Here is the initial output.

python event handler

Here is the output produced after first click of mouse over the button.

python event handler program

And here is the output produced after 5th click of mouse over the button.

python event handling

Python Online Test

« Previous Tutorial CodesCracker Home »

Follow/Like Us on Facebook

Subscribe Us on YouTube