Tuesday, January 22, 2019

tkinter examples - 2 (using frame)

To understand the utility of frames let's write a program to print 5 buttons, each for a vowel and an Ok button below these buttons. See the following code:

from tkinter import *

root = Tk()
vowel = 'AEIOU'
buttons = [0]*5

for i in range(5):
   
    buttons[i]=Button(text=vowel[i])
    buttons[i].grid(row=0,column=i)
   
ok_button = Button(text='Ok',font=('Verdana',24))
ok_button.grid(row=1,column=0)

mainloop()


The expected output of this program is something like this:



However when we run this program the output is as shown below:


The problem is with column 0 as there are two widgets there, the A button and the Ok button. Thus Tkinter will make that column big enough to handle the larger widget, the Ok button. One solution
to this problem is to include a columnspan attribute in the grid function as shown below:

ok_button.grid(row=1, column=0, columnspan=5) 

After incorporation the above mentioned change in the program we get the output as expected:



The other possible solution is to use a frame which hold other widgets and combine them into one large widget. So we'll create a frame to group all of the vowel buttons into one large widget as shown in the following program:

from tkinter import *

root = Tk()
vowel = 'AEIOU'
button_frame = Frame()
buttons = [0]*5

for i in range(5):
   
    buttons[i]=Button(button_frame,text=vowel[i])
    buttons[i].grid(row=0,column=i)
   
ok_button = Button(text='Ok',font=('Verdana',24))
button_frame.grid(row=0,column=0)
ok_button.grid(row=1,column=0)

mainloop()

We use Frame() method to create a frame for the buttons as shown by the following line:

button_frame = Frame()

After the frame is created we can include the widgets in the frame by passing the name of the frame as the first argument in the widget's declaration. This we did in the following line:

buttons[i]=Button(button_frame,text=vowel[i])

Here we added the buttons to the frame we created. Next we grid the button widgets and now the rows and columns will be relative to the frame.As we do for other widgets we grid the frame as shown by the following line:

button_frame.grid(row=0,column=0)

Thus using a frame is a more convenient approach than using a columnspan attribute in the grid function.

Make some programs on your own as GUI needs a lot practice. Till we meet next keep practicing and learning Python as Python is easy to learn!



 
Share:

0 comments:

Post a Comment