Home » Tkinter » How to Create Window in Python Using Tkinter?

How to Create Window in Python Using Tkinter?

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

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()

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()

See also: