In Tkinter, controlling the size of your application’s window is crucial for creating well-designed and user-friendly interfaces. See methods to set and manage the window size in Tkinter.
1. Using geometry()
The most common way to set the window size is by using the geometry()
method. This method allows you to specify the width and height of the window in pixels, as well as its initial position on the screen.
Example: Setting a Fixed Size
import tkinter as tk
root = tk.Tk()
root.title("Fixed Size Window")
root.geometry("600x400") # Width x Height
root.mainloop()
This code creates a window with a width of 600 pixels and a height of 400 pixels.
Example: Setting Size and Position
import tkinter as tk
root = tk.Tk()
root.title("Positioned Window")
root.geometry("600x400+100+50") # Width x Height + X + Y
root.mainloop()
This code sets the window size to 600×400 and positions the top-left corner 100 pixels from the left edge of the screen and 50 pixels from the top.
2. Using resizable()
The resizable()
method allows you to control whether the user can resize the window. You can disable resizing in either the horizontal or vertical direction, or both.
Example: Disabling Resizing
import tkinter as tk
root = tk.Tk()
root.title("Non-Resizable Window")
root.geometry("400x300")
root.resizable(False, False) # Disable both width and height resizing
root.mainloop()
In this example, the window cannot be resized by the user.
Example: Resizing Only in One Direction
import tkinter as tk
root = tk.Tk()
root.title("Resizable Height Only")
root.geometry("400x300")
root.resizable(False, True) # Disable width resizing, enable height resizing
root.mainloop()
Here, the user can only resize the window vertically.
3. Getting Screen Dimensions
You can retrieve the screen width and height to dynamically set the window size or position.
import tkinter as tk
root = tk.Tk()
root.title("Full Screen Window")
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
root.geometry(f"{screen_width}x{screen_height}+0+0") # Set to full screen
root.mainloop()
This code sets the window to full-screen size.
4. Setting Minimum and Maximum Sizes
You can set minimum and maximum window sizes to prevent the window from becoming too small or too large.
import tkinter as tk
root = tk.Tk()
root.title("Min/Max Size Window")
root.geometry("600x400")
root.minsize(300, 200) # Minimum width and height
root.maxsize(800, 600) # Maximum width and height
root.mainloop()
This code sets the initial size to 600×400, the minimum size to 300×200, and the maximum size to 800×600.