How to set a widget's size in Tkinter?


Tkinter widgets are the building blocks of any Tkinter GUI application. It is one of the very useful components of the application that helps to structure the application functionality. Consider a case where we want to set the size (width and height) of any widget. Tkinter has built-in width and height properties defined in geometry manager. Each geometry manager has different ways to configure the widget’s property.

For the pack geometry manager, we can specify the value of width in the constructor.However, there might be times when we want to add the advance padding (internal and external) in the widget which helps to manage the widget size and its look and feel. We can achieve this by adding padx or pady and ipadx or ipady.

Example

#Import the required Libraries
from tkinter import *
from tkinter import ttk

#Create an instance of tkinter frame
win = Tk()
#Set the geometry of tkinter frame
win.geometry("750x250")

#Create a StringVar to accept user input
var= StringVar(value= "Hey There! How are you doing?")
#Function definition to close the window
def close_win():
   win.destroy()

#Create a Label
label= Label(win,textvariable=var, font= ('Mistral 28 bold'), background= 'OrangeRed2', foreground="white")
label.pack(pady=20)

#Create a Button
ttk.Button(win, text= "Close", width= 20,command= close_win).pack(pady=20)

win.mainloop()

Output

Running the above code will display a window that contains a button widget and a label widget.

In the given Output, now update the value of width in the Button widget to change its size.

In the example we can also add the padding (internal and external) to resize the widget.

Updated on: 04-May-2021

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements