Tkinter pack() , grid() Method In Python
In this tutorial, we will discuss some basic functions that are used in GUI (Graphical User Interfaces) in Python using Tkinter. Tkinter is the standard GUI library for Python. In this, we have to see the description of the pack() and grid() method with their uses. So let’s start learning Tkinter pack() and grid() method in Python with some examples.
Tkinter pack() Method
Basically the pack() method is used to fix the parent widgets in blocks before placing them in parent window that we have created.
Syntax of pack() method
widget.pack( pack_options )
Here is the list of possible options or pack_options-
Python example program for pack() method
You can understand the following options by the given example. Try the following example by moving cursor on different buttons:
from tkinter import * window = Tk() frame = Frame(window) frame.pack() bottomframe = Frame(window) bottomframe.pack( side = BOTTOM ) redbutton = Button(frame, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frame, text="Brown", fg="brown") greenbutton.pack( side = LEFT ) bluebutton = Button(frame, text="Blue", fg="blue") bluebutton.pack( side = LEFT ) blackbutton = Button(bottomframe, text="Black", fg="black") blackbutton.pack( side = BOTTOM) window.mainloop()
Here the fg is used for providing the specific color to the button.
Tkinter grid() Method
Now, the grid method is used to fix the parent widgets in table-like structure before placing them in the main window that we have created.
Syntax of grid() method()
widget.grid( grid_options )
The grid_options are given below:
- ipadx, ipady
- padx, pady
Python example program for grid() method
We will understand the given options by an example that contain the following options. Try the following example by moving the cursor on different buttons:
from tkinter import * window = Tk() b=0 for r in range(6): for c in range(6): b=b+1 Button(window, text=str(b),borderwidth=1 ).grid(row=r,column=c) window.mainloop()
I am not giving any output here as I want you to go try and run on your machine.
You can also see for more information: