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:
1 2 3 4 5 6 7 |
btn0 = tkinter.Button(window, text="0") btn0.pack() btn1 = tkinter.Button(window, text="1") btn1.pack() btn2 = tkinter.Button(window, text="2") btn2.pack() ... |
Instead, you could add the ten buttons like this:
1 2 3 |
for num in range(10): btn = tkinter.Button(window, text=num) btn.pack(side=tkinter.LEFT) |
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:
You could even use a list to create the buttons, which would then allow you to add the other operator keys:
1 2 3 4 5 6 7 8 |
#create a list of buttons #you could also just write 'buttons = ['0','1','2',...] buttons = [i for i in range(10)] + ['+','-','/','x','='] print(buttons) for b in buttons: btn = tkinter.Button(window, text=b) btn.pack(side=tkinter.LEFT) |
Which would look like this:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#import the 'tkinter' module import tkinter #create a new window window = tkinter.Tk() #set the window title window.title("Colours") #set the window icon window.wm_iconbitmap('Icon.ico') #create a list variable containing colours colours = ['red','yellow','pink','green','purple','orange','blue'] #loop through each colour for c in colours: #create a new button, using the text/bg of the list item b = tkinter.Button(text=c, bg=c) #pack the button, filling up the X axis b.pack(fill=tkinter.X) #draw the window, and start the 'application' window.mainloop() |
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:
Challenge
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.