< Prev  |  Home  |  Next >

Dynamically Creating Widgets

Just like how you can use loops to write programs more efficiently, you can also use them to add lots of widgets to your GUI dynamically. For example, if you were to create a GUI for a simple calculator program, you’d be silly to create the ten buttons for the number keys like this:

Instead, you could add the ten buttons like this:

As you know, this loops through the numbers 0 to 9, and so therefore adds a button widget to the screen 10 times. Notice how the text for each of the buttons is also generated dynamically, using the current value of ‘num’. Notice also the use of the “side=tkinter.LEFT” argument to pack(), which packs the buttons from the left, like this:

Dynamically creating calculator buttons

You could even use a list to create the buttons, which would then allow you to add the other operator keys:

Which would look like this:

More calculator buttons

You can also use a loop, together with a list, to dynamically style the widgets that you create. In this next example, we use a list of colours to add colour and text to a set of labels:

The only new things here is that we’ve used the items in the list twice; once for the label text and again for its colour. Also, we’ve passed the argument “fill=tkinter.X” to pack(), so that the buttons fill the x-axis. This means that if we resize the window, the buttons stretch along the x-axis:

Dynamically changing the colour of a label


Create a skype-like ‘Voice over IP’ (VoIP) program that reads a list of people’s names, and adds them to the window, with a ‘Call’ button. It could look something like this:


Feel free to use what you have learnt so far to improve on the look of your window.

< Prev  |  Home  |  Next >