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.

Popularity: 35%

Related Posts

  • Using Menus in Tkinter
  • Tutorial Index
  • Creating a GUI in Python using Tkinter - Part 2
  • RSS reader - Part Four - Integrating with the GUI
  • Creating a GUI using PyGTK and Glade

  • del.icio.us del.icio.us blinklist

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

    Leave a Reply