Python Bibliotheca
Python resources for teachers and students.

Tkinter help

There are a lot of Tkinter tutorials on the Web. Try one of these.

Sample application

Here's code for a simple square root calculator:

from Tkinter import *
from tkMessageBox import showerror
from math import sqrt

class Calculator(Frame):
    def __init__(self):
        """Create an instance of a very simple calculator."""
        Frame.__init__(self)
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Sqrt Calculator')
        self.master.iconname('Sqrt')
        self.master.geometry('250x125')
        self.master.protocol("WM_DELETE_WINDOW", self.quit)
        self.bind_all("<Return>", self.calc)

        fInput = Frame(self)
        fInput.pack(pady=10)
        Label(fInput, text='x = ').pack(side=LEFT)
        self.number = StringVar()
        Entry(fInput, textvariable=self.number).pack(side=LEFT)

        fOutput = Frame(self)
        fOutput.pack(padx=5, pady=5)
        self.result_var = StringVar()
        self.result_var.set('Waiting for a number...')
        result = Label(fOutput,
                       textvariable=self.result_var).pack(pady=10)

        buttons = Frame(self)
        buttons.pack(padx=5, pady=5)
        Button(buttons, text='Calculate',
               command=self.calc).pack(side=LEFT, padx=3)
        Button(buttons, text='Quit',
               command=self.quit).pack(side=LEFT, padx=3)

    def calc(self, event=None):
        try:
            self.result_var.set("The square root of %s is %0.3f" % \
                (self.number.get(), sqrt(float(self.number.get()))) )
            self.number.set('')
        except ValueError:
            if self.number.get() == '':
                showerror('Entry error', 'You have to put a number in the blank.')
            else:
                showerror('Square root error',
                          "Can't find the square root of '%s'" % self.number.get())
            self.number.set('')
            self.result_var.set('Waiting for a number...')

Calculator().mainloop()

Running the program produces a GUI that looks like this:

Sqrt Calculator GUI

[ Copyright 2005, Tim Wilson ]

Comments, questions, or suggestions? Email the webmaster