Prerequisite: Python GUI – tkinter
Button size is static, which means the size of a button cannot be changed once it is defined by the user. The problem here is while resizing the window size, it can affect the button size problem. So the solution here is, make a dynamic button, which means the button size will change as per window size.
Let’s understand with step-by-step implementation:
Step 1#: Create Normal Tkinter Window
Python3
# Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry( "400x400" ) # Execute tkinter root.mainloop() |
Output:-
Step 2#: Add Buttons and set the grid.
Syntax:
Button(Object Name,text="Enter Text")
What is grid?
The grid() geometry manager organizes widgets in a table-like structure in the parent widget. The master widget is split into rows and columns, and each part of the table can hold a widget. It uses column, column span, ipadx, ipady, padx, pady, row, row span, and sticky.
Syntax:
Object_name.grid(row=row value,column=column value,**attributes)
Python3
# Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry( "500x500" ) # Create Buttons button_1 = Button(root,text = "Button 1" ) button_2 = Button(root,text = "Button 2" ) # Set grid button_1.grid(row = 0 ,column = 0 ) button_2.grid(row = 1 ,column = 0 ) # Execute tkinter root.mainloop() |
Output:
Step 3#: Set Columnconfigure & Rowconfigure for resize.
For the user interface to resize then, we’ll need to specify a positive weight to the columns that we’d like to expand. This is done using the Columnconfigure and Rowconfigure methods of the grid. This weight is relative. If two columns have the same weight, they’ll expand at the same rate.
What to do if the cell is larger than widget. By default, with sticky=”, widget is centered in its cell. sticky may be the string concatenation of zero or more of N, E, S, W, NE, NW, SE, and SW, compass directions indicating the sides and corners of the cell to which widget sticks.
“NSEW” means N+S+E+W
Code:-
Python3
# Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry( "500x500" ) # Specify Grid Grid.rowconfigure(root, 0 ,weight = 1 ) Grid.columnconfigure(root, 0 ,weight = 1 ) Grid.rowconfigure(root, 1 ,weight = 1 ) # Create Buttons button_1 = Button(root,text = "Button 1" ) button_2 = Button(root,text = "Button 2" ) # Set grid button_1.grid(row = 0 ,column = 0 ,sticky = "NSEW" ) button_2.grid(row = 1 ,column = 0 ,sticky = "NSEW" ) # Execute tkinter root.mainloop() |
Output: