codescracker


python

Python Event Handling



« Previous Tutorial CodesCracker Home »


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);
        self.grid();
        # below is the number of button clicks
        self.button_clicks = 0;
        self.create_widget();
    def create_widget(self):
        self.buttn = Button(self, text = "Total Clicks = 0");
        self.buttn["command"] = self.update_click_count;
        self.buttn.grid();
    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");
mainWindow.geometry("300x200");
app = MyApp(mainWindow);
mainWindow.mainloop();

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

« Previous Tutorial CodesCracker Home »








Tools
Calculator

Quick Links
Signup - Login - Give Online Test