Tkinter – Create Window

Creating a window in python and customizing it in some basic ways is very easy to do in python, in this post I will be showing how to create a main window and customize it a bit by changing the title and default size.

This code is written in Python 2.7 and will be using Tkinter to build the window.

First things first we need to add the bangline to the top of our script, I like to do this weather I am coding for use on a Windows or Linux machine as it wont hurt if its running on windows but usually causes errors if its missing in Linux. Then we will want to import everything from Tkinter, for the purpose of this demo we do not need everything imported from Tkinter but I like to do it that way so I don’t have to add a bunch of import lines as my program grows.

#!/usr/bin/python

from Tkinter import *

Next we will need to create the window object to work with. If you have a hard time understanding what is happening in the code below you can just consider it as assigning the physical window your creating to the variable name you choose. In this case I am calling it ‘main’ as it is the main window.

main = Tk()

At this point all we need to do is start a loop (highlighted) to create the window and we will get a blank window with your standard buttons you see in all windows

#!/usr/bin/python
from Tkinter import *

# creates the window frame and stores it as the variable 'main' for later use
main = Tk()  

# starts the loop to display the window and any contents (if there are any)
main.mainloop()  

Running the code above will give us a window that looks like this

As you can see its its this window is as default as you can get, but at this point you have a blank canvas for you to customize and build your UI on. In the following code I change the title of the window from ‘tk’ to ‘My cool new window!’, in addition to that I will set the default size of the window larger so it automatically gives me more space when the window opens.

#!/usr/bin/python
from Tkinter import *

# creates the window frame and stores it as the variable 'main' for later use
main = Tk()
main.title('My cool new window!')  # sets window title
main.geometry('500x500')  # sets default window size (pixels)

# starts the loop to display the window and any contents (if there are any)
main.mainloop()

When running this code this is how our window looks now, slightly larger and now with a new title.

At this point we are able to start customizing the content of the window, what widgets to display, what actions they will preform, etc.

Be the first to comment

Leave a Reply

Your email address will not be published.


*