Change Tkinter window size with variables – Dynamic

In this tutorial, we will learn how easily we can change Tkinter window size with variables dynamically in Python.

At first, I will show you how to do this using a custom function and then we will show you the basic program without using a function.

The idea is pretty much simple, and we will use the same geometry method and we will pass the value of width and height through variables.

import tkinter as tk
newWindow = tk.Tk()
newWindow.geometry("300x200")

def on_button_click():
    width = 700
    height = 700
    newWindow.geometry(f"{width}x{height}")

button = tk.Button(newWindow, text="Click Me", command=on_button_click)
button.pack(pady=20)
newWindow.mainloop()

So whenever the user will click on the button, it will run the function on_button_click()and it will make change the screensize according to the value of variable width and height.

Let’s make it simpler to understand.

import tkinter as tk
newWindow = tk.Tk()
width = 700
height = 700
newWindow.geometry(f"{width}x{height}")
newWindow.mainloop()

Using this you can set the size according to the value of width and height.

Now our final goal is to change the size from user input and make the change to the window size.

Change window size from user input in Tkinter:

import tkinter as tk

def set_geometry():
    width = width_entry.get()
    height = height_entry.get()
    newWindow.geometry(f"{width}x{height}")

newWindow = tk.Tk()
newWindow.geometry("300x200")

# Labels and entries for width and height
width_label = tk.Label(newWindow, text="Width:")
width_label.pack()
width_entry = tk.Entry(newWindow)
width_entry.pack()

height_label = tk.Label(newWindow, text="Height:")
height_label.pack()
height_entry = tk.Entry(newWindow)
height_entry.pack()

# Button to set the geometry
button = tk.Button(newWindow, text="Set Geometry", command=set_geometry)
button.pack()

newWindow.mainloop()

Output:

change window size in Tkinter dynamically with variables

Leave a Reply

Your email address will not be published. Required fields are marked *