A widget is a GUI component that is displayed on the screen and can perform a task as desired by the user. We create widgets as objects. For example, a push button is a widget that is nothing but an object of Button class. Similarly, label is a widget that is an object of Label class. Once a widget is created, it should be added to canvas or frame.
List of Widgets
The following are important widgets in Python:
In general, working with widgets takes the following four steps:
- Create the widgets that are needed in the program. A widget is a GUI component that is represented as an object of a class. For example, a push button is a widget that is represented as Button class object. As an example, suppose we want to create a push button, we can create an object to Button class as:
- When the user interacts with a widget, he will generate an event. For example, clicking on a push button is an event. Such events should be handled by writing functions or routines. These functions are called in response to the events. Hence they are called 'callback handlers ' or 'event handlers '. Other examples for events are pressing the Enter button, right clicking the mouse button, etc. As an example, let's write a function that may be called in response to button click.
- When the user clicks on the push button, that 'clicking' event should be linked with the 'callback handler' function.Then only the button widget will appear as if it is performing some task. As an example, let's bind the button click with the function as:
- The preceding 3 steps make the widgets ready for the user. Now, the user has to interact with the widgets. This is done by entering text from the keyboard or pressing mouse button. These are called events. These events are continuously monitored by our program with the help of a loop, called 'event loop'. As an example, we can use the mainloop() method that waits and processes the events as:
b = Button(f, text='My Button')
Here, 'f' is Frame object to which the button is added. 'My Button' is the text that is displayed on the button.
print('You have clicked me')