[Tutor] Simple calculator

Michael Lange klappnase at freenet.de
Wed Nov 1 12:31:59 CET 2006

Hi Joe,

On Tue, 31 Oct 2006 18:37:27 -0800
"Joe Cox" <jgcox39 at highstream.net> wrote:

> I found this simple calculator on the web:
> from Tkinter import *
> from math import *
> ###http://sunsite.uakom.sk/sunworldonline/swol-02-1998/swol-02-python.htmlBy
> Cameron Laird and Kathryn Soraiz...Getting Started with Python###
> def evaluate(event):
>         label['text'] = "Result:  " + str(eval(expression.get()))
> frame = Frame(None)
> entry = Entry(frame)
> entry['textvariable'] = expression = StringVar()
> entry.bind("", evaluate)
> label = Label(frame)
> button = Button(frame, text = "Submit", command = evaluate)
> frame.pack()
> entry.pack()
> label.pack()
> button.pack()
> frame.mainloop()
> I get this:
> >>> Traceback (most recent call last):
>   File
> "D:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py",
> line 310, in RunScript
>     exec codeObject in __main__.__dict__
>   File "D:\Python24\Calculator\Calc.py", line 12, in ?
>     entry.bind("", evaluate)
>   File "D:\Python24\lib\lib-tk\Tkinter.py", line 933, in bind
>     return self._bind(('bind', self._w), sequence, func, add)
>   File "D:\Python24\lib\lib-tk\Tkinter.py", line 888, in _bind
>     self.tk.call(what + (sequence, cmd))
> TclError: no events specified in binding

this code seems to be quite old, so I guess that the line

    entry.bind("", evaluate)

used to be legal in older version of Tk. I don't know what it is supposed
to do, though. Maybe there was some default event defined for such cases.
In today's Tk you need to specify an event sequence the callback should be bound to, like

    entry.bind("<Any-KeyRelease>", evaluate)

This does not work either, because you will get a syntax error on "incomplete"
expressions like "3*" when trying to type in "3*3" ,
so the evaluate() callback will have to catch this syntax error:

    def evaluate(event):
            label['text'] = "Result:  " + str(eval(expression.get()))
        except SyntaxError:

This still does not work, when you press the "submit" button you get:

Traceback (most recent call last):
  File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1345, in __call__
    return self.func(*args)
TypeError: evaluate() takes exactly 1 argument (0 given)

so the constructor must be changed like:

   def evaluate(event=None):

because the Tkinter.Button's "command" callback is called without any arguments
(again I don't know if this was different in old Tk versions).

With these changes at least the few simple examples I tried seem to work.

I hope this helps


More information about the Tutor mailing list