0
0
PythonHow-ToBeginner · 3 min read

How to Create a Window in Tkinter in Python

To create a window in tkinter, first import tkinter, then create an instance of Tk() which represents the main window, and finally call mainloop() to display it. This creates a simple window where you can add widgets and controls.
📐

Syntax

Here is the basic syntax to create a window in Tkinter:

  • import tkinter: Imports the Tkinter module.
  • root = tkinter.Tk(): Creates the main window object.
  • root.mainloop(): Starts the window's event loop to keep it open.
python
import tkinter

root = tkinter.Tk()
root.mainloop()
Output
A blank window appears on the screen until closed by the user.
💻

Example

This example creates a simple window with a title and a fixed size. It shows how to customize the window's appearance.

python
import tkinter

root = tkinter.Tk()
root.title('My First Tkinter Window')
root.geometry('300x200')  # Width x Height
root.mainloop()
Output
A window titled 'My First Tkinter Window' with size 300x200 pixels appears.
⚠️

Common Pitfalls

Common mistakes when creating a Tkinter window include:

  • Forgetting to call mainloop(), so the window closes immediately.
  • Not creating the Tk() instance before adding widgets.
  • Trying to create multiple Tk() instances instead of using Toplevel() for additional windows.
python
import tkinter

# Wrong: Missing mainloop, window won't stay open
root = tkinter.Tk()
root.title('No mainloop')

# Correct way
root = tkinter.Tk()
root.title('With mainloop')
root.mainloop()
Output
Only the second window stays open until closed by the user.
📊

Quick Reference

Summary tips for creating a Tkinter window:

  • Always import tkinter before use.
  • Create one main window with Tk().
  • Use mainloop() to keep the window visible.
  • Set window title with title() and size with geometry().

Key Takeaways

Import tkinter and create a main window using Tk() to start.
Call mainloop() to display and keep the window open.
Set window title and size with title() and geometry() methods.
Avoid creating multiple Tk() instances; use Toplevel() for extra windows.
Forgetting mainloop() is the most common reason the window closes immediately.