Press "Enter" to skip to content

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:

Have you found the answer to your question? If not, you can discuss it with me in the comments section below or join my Q&A community OrclQA.com for developers and ask your question. It is FREE.

Vinish Kapoor

Follow

Hi, I am a full stack developer and writing about development. I document everything I learn and help thousands of people. foxinfotech.in is created, written, and maintained by me; it is built on WordPress, and hosted by Bluehost. Connect with me on Facebook, Twitter, GitHub, and get notifications for new posts.

guest
11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments