Here we are providing basic tutorial in Tkinter to fit widgets in a layout. First consider the code given below.

Code

from tkinter import *

root = Tk()

one = Label(root, text="One", bg="red", fg="white")
one.pack()
two = Label(root, text="Two", bg="blue", fg="white")
two.pack(fill=X)
three = Label(root, text="Three", bg="green", fg="white")
three.pack(side=LEFT, fill=Y)

root.mainloop()


Output

output


Explanation of above code

Below section will give an explanation of the above Tkinter program. If you want to start from the beginning, please visit our Introduction to GUI tutorial.

First label

Label is another kind of widget. In above code, we created first label by calling the pre-defined Label function and storing it in object one. bg parameter is used to set the background whereas fg parameter is used to set the foreground. Then we simply packed it in the root window.

Second label

Second label is created in the same manner and is stored in two object. Difference arises in packing this label in the root window. A new parameter fill is being used here with pack() function and is set to value X. By using fill = X, this label can change its size according to the window's size in X direction.

Third label

Third label is created in the same manner and is stored in three object. Difference arises in packing this label in the root window. A new parameter fill is being used here with pack() function and is set to value Y. By using fill = Y, this label can change its size according to the window's size in Y direction.