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"""
        
        """Initialize the base class"""
        Frame.__init__(self,master)
        
        """Display the main window"""
        self.grid()
        
        """Create the Text"""
        self.HelloLabel = Label(master, text="Hello World!")
        self.HelloLabel.grid()
                
if __name__ == "__main__":
    guiFrame = GUIFramework()
    guiFrame.mainloop()

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"""
Frame.__init__(self,master)

"""Display the main window"""
self.grid()

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!")
self.HelloLabel.grid()

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()
    guiFrame.mainloop()

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"""
        Frame.__init__(self,master)
        
        """Set the Window Title"""
        self.master.title("Type Some Text")
        
        """Display the main window"
        with a little bit of padding"""
        self.grid(padx=10,pady=10)
        self.CreateWidgets()
       
    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()
    guiFrame.mainloop()

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.

selsine

del.icio.us del.icio.us

26 Responses to “Creating a GUI in Python using Tkinter”

  1. import this. » Blog Archive » Tkinter GUI tutorial
    Says:

    [...] Learning Python (mentioned earlier) has a rather nice tutorial up called Creating a GUI in Python using Tkinter: 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. [...]

  2. learning python » Blog Archive » Creating a GUI in Python using Tkinter - Part 2
    Says:

    [...] learning python one man’s journey into python… « Creating a GUI in Python using Tkinter [...]

  3. legalpython
    Says:

    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 ?

  4. selsine

    selsine
    Says:

    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.

  5. russ
    Says:

    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?

    Thanks!

  6. selsine

    selsine
    Says:

    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.

  7. Amyuqt
    Says:

    you very good in writing. write more!

  8. warrogy
    Says:

    The Author, you – genius…
    http://srubibablo.com
    Thanks much!

  9. K.E.M
    Says:

    Hi,

    I wish to create a dropdown with Tkinter. Is it possible?

    thanks very much

  10. Selva
    Says:

    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.

  11. da_perama
    Says:

    Very nice job introducing gui in python, simple and helpfull.
    Thank you.

  12. Abhishek
    Says:

    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

  13. yahnie
    Says:

    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..

  14. selsine

    selsine
    Says:

    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.

  15. dealing blac jack
    Says:

    dealing blac jack…

    Michele Lucifer questionings …

  16. Nadia
    Says:

    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.

  17. Nadia
    Says:

    I just found out. It’s tkinter and no longer Tkinter.

  18. afordable long term health ins quotas etna of chesapeake virginia
    Says:

    afordable long term health ins quotas etna of chesapeake virginia…

    cantors courters,Dijkstra wavers condemner weasels …

  19. Matteo
    Says:

    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/Tkinter.py, line 1650, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
    _tkinter.TclError: couldn’t connect to display :0\n
    can i help me ?
    thanks

  20. Antonio Pereira
    Says:

    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?

    thenks!

  21. Gord Goebel
    Says:

    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/__init__.py”, line 1402, in __call__
    return self.func(*args)
    File “/usr/lib/python3.1/idlelib/ScriptBinding.py”, line 156, in run_module_event
    interp.runcode(code)
    File “/usr/lib/python3.1/idlelib/PyShell.py”, line 698, in runcode
    self.interp.restart_subprocess()
    AttributeError: ‘ModifiedInterpreter’ object has no attribute ‘interp’

    What does it mean?

    Gordie.

  22. Gord Goebel
    Says:

    Fixed!

    For everyone else’s benefit (or at least, anybody as nube as I) I found this in another tutorial (http://www.ferg.org/thinking_in_tkinter/index.html):

    “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.

    Gordie.

  23. Gord Goebel
    Says:

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

    if environment IDLE:
    guiFrame.mainloop()

    Gordie.

  24. Ruwan Wickramarachchi
    Says:

    Thnx a lot. This is the best tutorial i’ve found for Tkinter GUI development.
    Written in a simple way along with the screencaps..

    Keep up the Good Work..!!

  25. Tom
    Says:

    Please check out my website for some great Tkinter examples!

    http://sites.google.com/site/pythonprojects0/home

  26. Tom
    Says:

    Please check out my website for some great Tkinter learning examples!

    http://sites.google.com/site/pythonprojects0/home

Leave a Reply

 

Popular Posts