Window in a room.

How to Create Window in Python Using Tkinter?

  • Python
  • 7 mins read

In this tutorial, you will learn how to create a window in Python using the Tkinter module library.

Python, a popular and versatile programming language, offers a variety of libraries and frameworks for creating graphical user interfaces (GUIs). One such library is Tkinter, which provides a simple and intuitive way to build windows, buttons, menus, and other interactive elements. If you're new to Tkinter and interested in learning how to create a window in Python, this guide is for you.

In this article, we will explore the basics of creating a window using Tkinter. We will cover the essential steps, from setting up the necessary environment to writing the code for a basic window. Whether you're a beginner or an experienced Python developer looking to dive into GUI development, this guide will help you get started with Tkinter and enable you to create your own custom windows with ease.

By the end of this article, you will have a solid foundation in Tkinter's window creation process. You'll understand how to set up the required libraries, create a blank window, and customize its attributes such as size, title, and appearance. Additionally, we'll touch upon handling events and adding interactive elements to your window.

Create a Window in Python Using Tkinter Example

The essential steps to creating a window using Tkinter.

  1. from tkinter import * # Import tkinter library in your Python Program.
  2. Window = Tk() # Declare a window object using Tk() method.
  3. Window.mainloop() # End the program using the mainloop() method for the window. This method holds the window active.

Complete Python Program

from tkinter import *

# declare the window
window = Tk()
# set window title
window.title("Python GUI App")
# set window width and height
window.configure(width=500, height=300)
# set window background color
window.configure(bg='lightgray')
window.mainloop()

This Python code demonstrates the creation of a basic graphical user interface (GUI) window using the Tkinter library. Let's break down the code step by step:

  1. from tkinter import *: This line imports all the classes, functions, and constants from the Tkinter library, allowing us to use them without prefixing them with the library name.
  2. window = Tk(): This line creates an instance of the Tk class, which represents the main window of the GUI application. It initializes a blank window and assigns it to the variable "window" so that we can refer to it later.
  3. window.title("Python GUI App"): This line sets the title of the window to "Python GUI App". The title appears in the title bar of the window.
  4. window.configure(width=500, height=300): This line sets the width and height of the window to 500 and 300 pixels, respectively. The configure method allows us to customize various attributes of the window.
  5. window.configure(bg='lightgray'): This line sets the background color of the window to "lightgray". The bg parameter specifies the background color, and we can provide a color name or a hexadecimal value.
  6. window.mainloop(): This line starts the main event loop of the window, which keeps the window displayed until it is closed by the user. The mainloop method continuously listens for events such as mouse clicks or keyboard inputs and responds accordingly.

When you run this code, it will create a window with the specified attributes: a title of "Python GUI App," a width of 500 pixels, a height of 300 pixels, and a background color of "lightgray". The window will remain open and responsive until the user closes it.

Output

Tkinter create window example

Moving a Window in Center

The following highlighted code will open the window in the center using geometry() method.

from tkinter import *

window = Tk()

window.title("Python GUI App")
window.configure(width=500, height=300)
window.configure(bg='lightgray')

# move window center
winWidth = window.winfo_reqwidth()
winwHeight = window.winfo_reqheight()
posRight = int(window.winfo_screenwidth() / 2 - winWidth / 2)
posDown = int(window.winfo_screenheight() / 2 - winwHeight / 2)
window.geometry("+{}+{}".format(posRight, posDown))

window.mainloop()

This Python code builds upon the previous example and adds additional functionality to center the window on the screen. Let's go through the code step by step:

1. `from tkinter import *`: This line imports all the classes, functions, and constants from the Tkinter library.

2. `window = Tk()`: This line creates an instance of the Tk class, representing the main window of the GUI application.

3. `window.title("Python GUI App")`: This line sets the title of the window to "Python GUI App".

4. `window.configure(width=500, height=300)`: This line sets the width and height of the window to 500 and 300 pixels, respectively.

5. `window.configure(bg='lightgray')`: This line sets the background color of the window to "lightgray".

6. `winWidth = window.winfo_reqwidth()`: This line retrieves the requested width of the window.

7. `winHeight = window.winfo_reqheight()`: This line retrieves the requested height of the window.

8. `posRight = int(window.winfo_screenwidth() / 2 - winWidth / 2)`: This line calculates the horizontal position for centering the window. It divides the screen width by 2 and subtracts half of the window width.

9. `posDown = int(window.winfo_screenheight() / 2 - winHeight / 2)`: This line calculates the vertical position for centering the window. It divides the screen height by 2 and subtracts half of the window height.

10. `window.geometry("+{}+{}".format(posRight, posDown))`: This line sets the window's position on the screen using the calculated horizontal and vertical positions.

11. `window.mainloop()`: This line starts the main event loop of the window, which keeps the window displayed until it is closed by the user.

When you run this code, it creates a window with the specified attributes, such as the title, size, and background color. Additionally, it calculates the center position of the screen and moves the window to that position. The window will remain open and responsive until the user closes it.

Creating a Window in Python Using Pygame Example

Prerequisites

Before we start, you need to have Python and Pygame installed on your computer. If you haven't installed Pygame yet, you can do so by opening your command prompt (Windows) or terminal (Mac and Linux) and typing:

pip install pygame

Here's a complete example that creates a window and closes it when you click the close button:

import pygame

# Initialize Pygame
pygame.init()

# Set up the window dimensions
width = 800
height = 600

# Create the window
window = pygame.display.set_mode((width, height))

# Set the window title
pygame.display.set_caption("My Game")

# Game loop
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

# Quit Pygame
pygame.quit()

Certainly, here's a brief explanation of each part of the code:

  1. import pygame: Imports the Pygame library for use in the program.
  2. pygame.init(): Initializes the Pygame library.
  3. width = 800 and height = 600: Sets the dimensions of the game window to 800 pixels wide and 600 pixels high.
  4. window = pygame.display.set_mode((width, height)): Creates the game window with the specified dimensions and assigns it to the window variable.
  5. pygame.display.set_caption("My Game"): Sets the title of the game window to "My Game."
  6. running = True: Initializes a variable running as True to control the game loop.
  7. Game Loop: This loop keeps the game running until running becomes False.
  8. Event Handling: Iterates through events (like mouse clicks or keyboard presses) that occur during the game.
  9. Checking for the QUIT Event: Checks if the current event is the "QUIT" event (closing the window), and if so, sets running to False to exit the game loop.
  10. pygame.quit(): Cleans up and quits the Pygame library when the game is done.

Conclusion

Congratulations! You've learned how to create a window in Python using Tkinter and Pygame. This is the first step in creating your own games and graphical applications. Experiment with different window sizes and titles to customize your projects. Keep learning and exploring, and soon you'll be making amazing applications of your own!

See also:

This Post Has 14 Comments

  1. Mik

    Hello Vinish,

    I'm looking for a way to use Tkinter to display a second fullscreen window on my MacBook's external monitor, but I can't find a solution anywhere....
    On the internal monitor it's not a problem.

    Greetings, Mik

    1. Daniel

      Do you know how to open multiple of these at once?

  2. Daniel

    Hello there. I would like to know how to open multiple of these at once. please let me know if you can help thanks

    1. Vinish Kapoor

      In the below example, it will open two windows (window and window1) at once:

      from tkinter import *
      
      # declare the window
      window = Tk()
      # set window title
      window.title("Python GUI App")
      # set window width and height
      window.configure(width=500, height=300)
      # set window background color
      window.configure(bg='lightgray')
      
      window1 = Tk()
      # set window title
      window1.title("Python GUI App")
      # set window width and height
      window1.configure(width=500, height=300)
      # set window background color
      window1.configure(bg='lightgray')
      window1.mainloop()
      
  3. Alpere

    How can I code, that each string in my array is in a separate line?

    1. Vinish Kapoor

      Try this:

      print(*yourlist, sep = "\n") 

  4. Aaqil

    hey I have two codes in one file please help on how to make a window with the code below in it

    from tkinter import *
    
    # declare the window
    window = Tk()
    # set window title
    window.title("Celsius To Farenhite")
    # set window width and height
    window.configure(width=500, height=500)
    # set window background color
    window.configure(bg='white')
    window.mainloop()
    
    def fahrenheit_from(celsius):
        """Convert Celsius to Fahrenheit degrees."""
        try:
            fahrenheit = float(celsius) * 9 / 5 + 32
            fahrenheit = round(fahrenheit, 3)  # Round to three decimal places
            return str(fahrenheit)
        except ValueError:
            return "invalid input"
    
    if __name__ == "__main__":
        celsius = input("Celsius: ")
        print("Fahrenheit:", fahrenheit_from(celsius))
    
  5. Iram

    Hi!
    How Can I Print In Some Text In The Window?

    1. Eggdog

      After you are done initalizing the window, put this code before root.mainloop()

      p_one = Text(root, height=0)
      p_one.pack()
      

      You should also make sure to change root to your window name

    2. mauuuuu

      But with this function the whole height and width of the window are readjusted to the pack() values. Is it possible to make this a small widget in the original main window?

  6. USR287

    It is NOT working on VS code for ubuntu linux if you can fix this i would be delighted

  7. fazee

    how to create a window inside a parent window?

  8. Siri

    Hello there how do you add a play and endgame button to the window

    1. Vinish Kapoor

      You can try this:

      import tkinter as tk
      
      def play_game():
          print("The game is starting!")
      
      def end_game():
          print("The game has ended.")
          root.destroy()
      
      root = tk.Tk()
      root.title("Game Window")
      
      play_button = tk.Button(root, text="Play Game", command=play_game)
      play_button.pack()
      
      end_button = tk.Button(root, text="End Game", command=end_game)
      end_button.pack()
      
      root.mainloop()
      
      

Comments are closed.