Python Widgets

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.

The following are important widgets in Python:

  • Button
  • Label
  • Message
  • Text
  • Scrollbar
  • Checkbutton
  • Radiobutton
  • Entry
  • Spinbox
  • Listbox
  • Menu

In general, working with widgets takes the following four steps:

  1. 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:
  2. 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.

  3. 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.
  4. def buttonClick(self):

    print('You have clicked me')

  5. 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:
  6. b.bind('<Button-1>', buttonClick)

  7. 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: