Tkinter Window Manipulation

Tkinter Window Manipulation

Summary

In this tutorial, you’ll learn how to manipulate various attributes of a Tkinter window.

Creating a Simple Window

Let's start with a simple program that creates a window:

import tkinter as tk

app = tk.Tk()
app.mainloop()
Code copied!

Output

The root window has a title that defaults to 'tk' and includes three system buttons: Minimize, Maximize, and Close.

Changing the Window Title

To change the window’s title, use the title() method:

import tkinter as tk

app = tk.Tk()
app.title('Tkinter Window Demo')
app.mainloop()
Code copied!

Changing Window Size and Location

The position and size of a window are determined by its geometry, specified as widthxheight±x±y.

app.geometry('600x400+50+50')
Code copied!

This sets the window size to 600x400 pixels and positions it 50 pixels from the top and left of the screen.

Centering the Window

To center the window on the screen, you can use the following code:

import tkinter as tk

app = tk.Tk()
app.title('Tkinter Window - Center')

window_width = 300
window_height = 200

screen_width = app.winfo_screenwidth()
screen_height = app.winfo_screenheight()

center_x = int(screen_width / 2 - window_width / 2)
center_y = int(screen_height / 2 - window_height / 2)

app.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
app.mainloop()
Code copied!

Resizing Behavior

By default, windows can be resized. To prevent resizing, use the resizable() method:

app.resizable(False, False)
Code copied!

Fixed Size Example

This code snippet creates a window with a fixed size:

import tkinter as tk

app = tk.Tk()
app.title('Fixed Size Window')
app.geometry('600x400')
app.resizable(False, False)
app.mainloop()
Code copied!

Transparency

Set the window's transparency using the alpha channel:

app.attributes('-alpha', 0.5)
Code copied!

Example of a Transparent Window

import tkinter as tk

app = tk.Tk()
app.title('Transparent Window')
app.geometry('600x400')
app.attributes('-alpha', 0.5)
app.mainloop()
Code copied!

Changing the Default Icon

To change the default icon, follow these steps:

  • Prepare an image in .ico format.
  • Place the icon in an accessible folder.
  • Call the iconbitmap() method.
import tkinter as tk

app = tk.Tk()
app.title('Custom Icon Window')
app.iconbitmap('path/to/your/icon.ico')
app.mainloop()
Code copied!

Conclusion

In this tutorial, you learned how to:

  • Change the title of a Tkinter window.
  • Adjust the size and position of the window.
  • Set window resizing behavior.
  • Implement transparency and modify the icon.

These techniques will help you create more customized and user-friendly applications using Tkinter.