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:

And running it in Windows Xp gives you:

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:

That shows this dialog when the button is pressed:

Links that helped me get through this post:
- http://www.pythonware.com/library/tkinter/introduction/
- http://infohost.nmt.edu/tcc/help/pubs/tkinter/
If you like this post remember to digg it.



February 15th, 2006 at 7:40 pm
[...] 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. [...]
February 19th, 2006 at 5:19 pm
[...] learning python one man’s journey into python… « Creating a GUI in Python using Tkinter [...]
October 22nd, 2006 at 7:02 am
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 ?

selsine Says:October 26th, 2006 at 8:15 am
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.
May 1st, 2007 at 7:25 am
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!

selsine Says:May 5th, 2007 at 10:48 am
Hi Russ,
If you wanted to do this, simply call the entry field’s get() function:
That would set myvariable to be equal to the contents of the entry field.
October 23rd, 2007 at 8:16 am
you very good in writing. write more!
November 30th, 2007 at 7:47 am
The Author, you – genius…
http://srubibablo.com
Thanks much!
May 9th, 2008 at 2:50 am
Hi,
I wish to create a dropdown with Tkinter. Is it possible?
thanks very much
May 12th, 2008 at 4:58 am
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.
May 15th, 2008 at 1:52 am
Very nice job introducing gui in python, simple and helpfull.
Thank you.
June 2nd, 2008 at 1:54 am
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
August 18th, 2008 at 9:35 pm
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..

selsine Says:August 19th, 2008 at 8:21 am
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.
November 10th, 2008 at 9:32 am
dealing blac jack…
Michele Lucifer questionings …
March 5th, 2009 at 7:14 am
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.
March 6th, 2009 at 4:47 am
I just found out. It’s tkinter and no longer Tkinter.
June 1st, 2009 at 2:04 am
afordable long term health ins quotas etna of chesapeake virginia…
cantors courters,Dijkstra wavers condemner weasels …
September 11th, 2009 at 9:46 am
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
September 16th, 2009 at 4:38 pm
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!