Creating a GUI in Python using Tkinter

Up until now we’ve focused on python applications that only run in the command line. For a lot of tasks this is great, but in order to be really impressive we’re going to want to create a GUI for some of our python applications.

There are a lot of python GUI toolkits out there, but for our first application we are going to use Tkinter, which is considered somewhat of a standard right now and is installed when pyhon is installed. Another nice thing about the Tkinter GUI is that it is cross platform and offers a native look and feel on *nix, Windows, and OS X.

Tkinter Example One

So lets start off with a simply “Hello World” GUI app:

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

class GUIFramework(Frame):
    """This is the GUI"""
    def __init__(self,master=None):
        """Initialize the base class"""
        """Display the main window"""
        """Create the Text"""
        self.HelloLabel = Label(master, text="Hello World!")
if __name__ == "__main__":
    guiFrame = GUIFramework()

Running this on OS X results in the following:

hello world python gui

And running it in Windows Xp gives you:

hello world python gui

As you can see the code used to create the GUI is pretty simple and easy to understand, but it is actually more complicated then need be because it uses classes. But since I’ll be using classes whenever building a GUI I thought that this was the best starting point. We start off by importing the Tkinter library into our program using this following:

from Tkinter import *

After that we create a class called GUIFramework, which is the class that will be used to great the GUI elements in Tkinter and uses the Tkinter frame class as its base. For now all the work that we do is done in the __init__ function.

There we first initialize the base class (which will initialize Tkinter) and then tell ourselves to be visible:

"""Initialise the base class"""

"""Display the main window"""

To display ourselves we use the grid geometry manager, the grid geometry manager is a straight forward way to display widgets and position them. Since we have no other widgets in this example the defaults are fine, take a look at example two for for information on widget placement using the grid function.

Next is the process of creating the HelloWorld label widget, which is a member of the GUIFramework class, and setting it to be visible. It’s a good idea to make your widgets members of the class in case you need to access them later, but if you’re sure that you’ll never have to access them later, you can just create them locally.

self.HelloLabel = Label(master, text="Hello World!")

After that all the other processing is done in the “main” section of our code where we initialize our class and tell it to enter the “mainloop”. The “mainloop” is basically the application responding to events:

if __name__ == "__main__":
    guiFrame = GUIFramework()

Tkinter Example Two

Next I’ll show you a more complicated example, I won’t go into specifics with this one since it’s still pretty simple. But if you have any questions about the following code feel free to ask via a comment.

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

class GUIFramework(Frame):
    """This is the GUI"""
    def __init__(self,master=None):
        """Initialize yourself"""
        """Initialise the base class"""
        """Set the Window Title"""
        self.master.title("Type Some Text")
        """Display the main window"
        with a little bit of padding"""
    def CreateWidgets(self):
        """Create all the widgets that we need"""
        """Create the Text"""
        self.lbText = Label(self, text="Enter Text:")
        self.lbText.grid(row=0, column=0)
        """Create the Entry, set it to be a bit wider"""
        self.enText = Entry(self)
        self.enText.grid(row=0, column=1, columnspan=3)
        """Create the Button, set the text and the 
        command that will be called when the button is clicked"""
        self.btnDisplay = Button(self, text="Display!", command=self.Display)
        self.btnDisplay.grid(row=0, column=4)
    def Display(self):
        """Called when btnDisplay is clicked, displays the contents of self.enText"""
        tkMessageBox.showinfo("Text", "You typed: %s" % self.enText.get())    
if __name__ == "__main__":
    guiFrame = GUIFramework()

This creates the following window:
hello world python gui

That shows this dialog when the button is pressed:
hello world python gui

Links that helped me get through this post:

If you like this post remember to digg it.

31 thoughts on “Creating a GUI in Python using Tkinter”

  1. Is it possible to mix gui commands and console commands ? So that i can show
    a gui messagebox and then use the normal console commands in my script ?

  2. Hey legalpython,

    I’m not exactly sure what you mean by console commands? Do you mean something like outputting text to the command line (or console)? If so yes it is totally possible to mix both commands.

    You could definitely have a console application that displays a message box from time to time. There is nothing, that I know of, in python that would stop you from doing this.

  3. A (hopefully not) dumb question…..

    I am trying to save the test typed into the “Entry” field to a file. How would I “capture” that text in a variable?


  4. Hi Russ,

    If you wanted to do this, simply call the entry field’s get() function:

    myvariable = self.enText.get()

    That would set myvariable to be equal to the contents of the entry field.

  5. Hai,
    your website tutorials are really good. Could you please tell me where I can find a complete tutorials to Tkinter. It would be quite helpful for me as i am a beginner in GUI building using python.

  6. Thanks a lot I am able to design some window now. I need more interactive think like I want to provide Hyperlink to the text dispalyed in window

  7. Is it possible to have a hyperlink in the webpage and upon clicking the said hyperlink the tkinter will appear? if so, then how could it be done? thanks in advance for the reply..

  8. Hi yahnie,

    I don’t think it’s possible. It may be and I just don’t know about it. But it seems as though that’s a mix or server and client stuff.

  9. Pingback: dealing blac jack
  10. Hello,

    I am learning Python through “Think Python an Intro to software design” by Allen. I am now in Chapter 3. This book is based on v2.* and there is already a v3. However, the book has footnotes regarding some changes in v2, so I decided to use IDLE for v3.

    Since I am interested in GUI programming in Python, I was disappointed when Example One code did not run in IDLE v3. I need your advise whether to use v2 of IDLE and learn later the v3.

  11. Hi, i’m try to run this application but i received this messagge from the interpreter :

    _default_root = Tk()
    File /usr/lib/python2.5/lib-tk/, line 1650, in __init__ = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
    _tkinter.TclError: couldn’t connect to display :0\n
    can i help me ?

  12. How about if I wish to add 2 textboxes instead of just one?

    I know how to create them, connect them, but what can I do con concatenate the contents of 2 or more text boxes?


  13. I ran the Hello World GUI example (in IDLE3) and it worked fine but when I closed it the window disappeared but I didn’t get a new prompt in the python shell and when I tried to run it again I got a popup warning me that there was a script still running plus the following text in the python shell.

    Exception in Tkinter callback
    Traceback (most recent call last):
    File “/usr/lib/python3.1/tkinter/”, line 1402, in __call__
    return self.func(*args)
    File “/usr/lib/python3.1/idlelib/”, line 156, in run_module_event
    File “/usr/lib/python3.1/idlelib/”, line 698, in runcode
    AttributeError: ‘ModifiedInterpreter’ object has no attribute ‘interp’

    What does it mean?


  14. Fixed!

    For everyone else’s benefit (or at least, anybody as nube as I) I found this in another tutorial (

    “Note that you should not run these programs under IDLE. IDLE is itself a Tkinter application, with its own “mainloop” that will conflict with the mainloop in these programs. If you really want to view and run these programs using IDLE, then — for each program — you should comment out the “mainloop” statement in the program before running it.”

    Hope this saves someone else from pulling out their hair.


  15. So the next question would be whether there is a way to have something like the following:

    if environment IDLE:


  16. My name is Wayne Reuvers, and I can make your website UNHACKABLE, GUARANTEED.
    Do not put yourself at risk.
    Call 1-845-351-5100 to contact a representative. Email me at for
    a live demonstration.
    FREE CHALLENGE: If you are able to hack our website ( OUR
    SERVICES ARE FREE! Do not waste another moment. Call
    us now. ?? ???? ?? !

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>