Creating a Calculator With wxPython
Learn how to create a calculator using the dreaded eval() fucntion in Python while learning how to keep it under control.
Join the DZone community and get the full member experience.
Join For Free
a lot of beginner tutorials start with “hello world” examples. there are plenty of websites that use a calculator application as a kind of “hello world” for gui beginners. calculators are a good way to learn because they have a set of widgets that you need to lay out in an orderly fashion. they also require a certain amount of logic to make them work correctly. for this calculator, let’s focus on being able to do the following:
- addition
- subtraction
- multiplication
- division
i think that supporting these four functions is a great starting place and also give you plenty of room for enhancing the application on your own.
figuring out the logic
one of the first items that you will need to figure out is how to actually execute the equations that you build. for example, let’s say that you have the following equation:
1 + 2 * 5
what is the solution? if you read it left-to-right, the solution would seem to be 3 * 5 or 15. but multiplication has a higher precedence than addition, so it would actually be 10 + 1 or 11. how do you figure out precedence in code? you could spend a lot of time creating a string parser that groups numbers by the operand or you could use python’s built-in `eval` function. the
eval()
function is short for evaluate and will evaluate a string as if it was python code.
a lot of python programmers actually discourage the user of
eval()
. let’s find out why.
is
eval()
evil?
the
eval()
function has been called “evil” in the past because it allows you to run strings as code, which can open up your application’s to nefarious evil-doers. you have probably read about sql injection where some websites don’t properly escape strings and accidentally allowed dishonest people to edit their database tables by running sql commands via strings. the same concept can happen in python when using the
eval()
function. a common example of how eval could be used for evil is as follows:
eval("__import__('os').remove('file')")
this code will import python’s
os
module and call its
remove()
function, which would allow your users to delete files that you might not want them to delete. there are a couple of approaches for avoiding this issue:
-
don’t use
eval()
-
control what characters are allowed to go to
eval()
since you will be creating the user interface for this application, you will also have complete control over how the user enters characters. this actually can protect you from eval’s insidiousness in a straight-forward manner. you will learn two methods of using wxpython to control what gets passed to
eval()
, and then you will learn how to create a custom
eval()
function at the end of the article.
designing the calculator
let’s take a moment and try to design a calculator using the constraints mentioned at the beginning of the chapter. here is the sketch i came up with:
note that you only care about basic arithmetic here. you won’t have to create a scientific calculator, although that might be a fun enhancement to challenge yourself with. instead, you will create a nice, basic calculator.
let’s get started!
creating the initial calculator
whenever you create a new application, you have to consider where the code will go. does it go in the
wx.frame
class, the
wx.panel
class, some other class or what? it is almost always a mix of different classes when it comes to wxpython. as is the case with most wxpython applications, you will want to start by coming up with a name for your application. for simplicity’s sake, let’s call it
wxcalculator.py
for now.
the first step is to add some imports and subclass the
frame
widget. let’s take a look:
import wx
class calcframe(wx.frame):
def __init__(self):
super().__init__(
none, title="wxcalculator",
size=(350, 375))
panel = calcpanel(self)
self.setsizehints(350, 375, 350, 375)
self.show()
if __name__ == '__main__':
app = wx.app(false)
frame = calcframe()
app.mainloop()
this code is very similar to what you have seen in the past. you subclass
wx.frame
and give it a title and initial size. then you instantiate the panel class,
calcpanel
(not shown) and you call the
setsizehints()
method. this method takes the smallest (width, height) and the largest (width, height) that the frame is allowed to be. you may use this to control how much your frame can be resized or in this case, prevent any resizing. you can also modify the frame’s style flags in such a way that it cannot be resized too.
here’s how:
class calcframe(wx.frame):
def __init__(self):
no_resize = wx.default_frame_style & ~ (wx.resize_border |
wx.maximize_box)
super().__init__(
none, title="wxcalculator",
size=(350, 375), style=no_resize)
panel = calcpanel(self)
self.show()
take a look at the
no_resize
variable. it is creating a
wx.default_frame_style
and then using bitwise operators to remove the resizable border and the maximize button from the frame.
let’s move on and create the
calcpanel
:
class calcpanel(wx.panel):
def __init__(self, parent):
super().__init__(parent)
self.last_button_pressed = none
self.create_ui()
i mentioned this in an earlier chapter, but i think it bears repeating here. you don’t need to put all your interfacer creation code in the
init
method. this is an example of that concept. here you instantiate the class, set the
last_button_pressed
attribute to
none
and then call
create_ui()
. that is all you need to do here.
of course, that begs the question. what goes in the
create_ui()
method? well, let’s find out!
def create_ui(self):
main_sizer = wx.boxsizer(wx.vertical)
font = wx.font(12, wx.modern, wx.normal, wx.normal)
self.solution = wx.textctrl(self, style=wx.te_right)
self.solution.setfont(font)
self.solution.disable()
main_sizer.add(self.solution, 0, wx.expand|wx.all, 5)
self.running_total = wx.statictext(self)
main_sizer.add(self.running_total, 0, wx.align_right)
buttons = [['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['.', '0', '', '+']]
for label_list in buttons:
btn_sizer = wx.boxsizer()
for label in label_list:
button = wx.button(self, label=label)
btn_sizer.add(button, 1, wx.align_center|wx.expand, 0)
button.bind(wx.evt_button, self.update_equation)
main_sizer.add(btn_sizer, 1, wx.align_center|wx.expand)
equals_btn = wx.button(self, label='=')
equals_btn.bind(wx.evt_button, self.on_total)
main_sizer.add(equals_btn, 0, wx.expand|wx.all, 3)
clear_btn = wx.button(self, label='clear')
clear_btn.bind(wx.evt_button, self.on_clear)
main_sizer.add(clear_btn, 0, wx.expand|wx.all, 3)
self.setsizer(main_sizer)
this is a decent chunk of code, so let’s break it down a bit:
def create_ui(self):
main_sizer = wx.boxsizer(wx.vertical)
font = wx.font(12, wx.modern, wx.normal, wx.normal)
here you create the sizer that you will need to help organize the user interface. you will also create a
wx.font
object, which is used to modifying the default font of widgets like
wx.textctrl
or
wx.statictext
. this is helpful when you want a larger font size or a different font face for your widget than what comes as the default.
self.solution = wx.textctrl(self, style=wx.te_right)
self.solution.setfont(font)
self.solution.disable()
main_sizer.add(self.solution, 0, wx.expand|wx.all, 5)
these next three lines create the
wx.textctrl
, set it to right-justified (wx.te_right), set the font and
disable()
the widget. the reason that you want to disable the widget is because you don’t want the user to be able to type any string of text into the control.
as you may recall, you will be using
eval()
for evaluating the strings in that widget, so you can’t allow the user to abuse that. instead, you want fine-grained control over what the user can enter into that widget.
self.running_total = wx.statictext(self)
main_sizer.add(self.running_total, 0, wx.align_right)
some calculator applications have a running total widget underneath the actual “display.” a simple way to add this widget is via the
wx.statictext
widget.
now let’s add main buttons you will need to use a calculator effectively:
buttons = [['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['.', '0', '', '+']]
for label_list in buttons:
btn_sizer = wx.boxsizer()
for label in label_list:
button = wx.button(self, label=label)
btn_sizer.add(button, 1, wx.align_center|wx.expand, 0)
button.bind(wx.evt_button, self.update_equation)
main_sizer.add(btn_sizer, 1, wx.align_center|wx.expand)
here you create a list of lists. in this data structure, you have the primary buttons used by your calculator. you will note that there is a blank string in the last list that will be used to create a button that doesn’t do anything. this is to keep the layout correct. theoretically, you could update this calculator down the road such that that button could be "percentage" or do some other function.
the next step is to createthee buttons, which you can do by looping over the list. each nested list represents a row of buttons. so for each row of buttons, you will create a horizontally oriented
wx.boxsizer
and then loop over the row of widgets to add them to that sizer. once every button is added to the row sizer, you will add that sizer to your main sizer. note that each of these button’s is bound to the
update_equation
event handler as well.
now you need to add the equals button and the button that you may use to clear your calculator:
equals_btn = wx.button(self, label='=')
equals_btn.bind(wx.evt_button, self.on_total)
main_sizer.add(equals_btn, 0, wx.expand|wx.all, 3)
clear_btn = wx.button(self, label='clear')
clear_btn.bind(wx.evt_button, self.on_clear)
main_sizer.add(clear_btn, 0, wx.expand|wx.all, 3)
self.setsizer(main_sizer)
in this code snippet you create the “equals” button which you then bind to the
on_total
event handler method. you also create the “clear” button, for clearing your calculator and starting over. the last line sets the panel’s sizer.
let’s move on and learn what most of the buttons in your calculator are bound to:
def update_equation(self, event):
operators = ['/', '*', '-', '+']
btn = event.geteventobject()
label = btn.getlabel()
current_equation = self.solution.getvalue()
if label not in operators:
if self.last_button_pressed in operators:
self.solution.setvalue(current_equation + ' ' + label)
else:
self.solution.setvalue(current_equation + label)
elif label in operators and current_equation is not '' \
and self.last_button_pressed not in operators:
self.solution.setvalue(current_equation + ' ' + label)
self.last_button_pressed = label
for item in operators:
if item in self.solution.getvalue():
self.update_solution()
break
this is an example of binding multiple widgets to the same event handler. to get information about which widget has called the event handler, you can call the "event" object’s
geteventobject()
method. this will return whatever widget it was that called the event handler. in this case, you know you called it with a wx.button instance, so you know that
wx.button
has a
getlabel()
method which will return the label on the button. then you get the current value of the solution text control.
next, you want to check if the button’s label is an operator (i.e., /, *, -, +). if it is, you will change the text controls value to whatever is currently in it plus the label. on the other hand, if the label is
not
an operator, then you want to put a space between whatever is currently in the text box and the new label. this is for presentation purposes. you could technically skip the string formatting if you wanted to.
the last step is to loop over the operands and check if any of them are currently in the equation string. if they are, then you will call the
update_solution()
method and break out of the loop.
now you need to write the
update_solution()
method:
def update_solution(self):
try:
current_solution = str(eval(self.solution.getvalue()))
self.running_total.setlabel(current_solution)
self.layout()
return current_solution
except zerodivisionerror:
self.solution.setvalue('zerodivisionerror')
except:
pass
here is where the “evil”
eval()
makes its appearance. you will extract the current value of the equation from the text control and pass that string to
eval()
. then convert that result back to a string so you can set the text control to the newly calculated solution. you want to wrap the whole thing in a try/except statement to catch errors, such as the
zerodivisionerror
. the last
except
statement is known as a
bare except
and should really be avoided in most cases. for simplicity, i left it in there, but feel free to delete those last two lines if they offend you.
the next method you will want to take a look at is the
on_clear()
method:
def on_clear(self, event):
self.solution.clear()
self.running_total.setlabel('')
this code is pretty straight forward. all you need to do is call your solution text control’s
clear()
method to empty it out. you will also want to clear the "running_total" widget, which is an instance of
wx.statictext
. that widget does not have a
clear()
method, so instead you will call
setlabel()
and pass in an empty string.
the last method you will need to create is the
on_total()
event handler, which will calculate the total and also clear out your running total widget:
def on_total(self, event):
solution = self.update_solution()
if solution:
self.running_total.setlabel('')
here you can call the
update_solution()
method and get the result. assuming that all went well, the solution will appear in the main text area and the running total will be emptied.
here is what the calculator looks like when i ran it on a mac:
and here is what the calculator looks like on windows 10:
let’s move on and learn how you might allow the user to use their keyboard in addition to your widgets to enter an equation.
using character events
most calculators will allow the user to use the keyboard when entering values. in this section, i will show you how to get started adding this ability to your code. the simplest method to use to make this work is to bind the
wx.textctrl
to the
wx.evt_text
event. i will be using this method for this example. however, another way that you could do this would be to catch
wx.evt_key_down
and then analyze the key codes. that method is a bit more complex though.
the first item that we need to change is our
calcpanel
‘s constructor:
# wxcalculator_key_events.py
import wx
class calcpanel(wx.panel):
def __init__(self, parent):
super().__init__(parent)
self.last_button_pressed = none
self.whitelist = ['0', '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'-', '+', '/', '*', '.']
self.on_key_called = false
self.empty = true
self.create_ui()
here you add a
whitelist
attribute and a couple of simple flags,
self.on_key_called
and,
self.empty
. the white list is the only characters that you will allow the user to type in your text control. you will learn about the flags when we actually get to the code that uses them.
but first, you will need to modify the
create_ui()
method of your panel class. for brevity, i will only reproduce the first few lines of this method:
def create_ui(self):
main_sizer = wx.boxsizer(wx.vertical)
font = wx.font(12, wx.modern, wx.normal, wx.normal)
self.solution = wx.textctrl(self, style=wx.te_right)
self.solution.setfont(font)
self.solution.bind(wx.evt_text, self.on_key)
main_sizer.add(self.solution, 0, wx.expand|wx.all, 5)
self.running_total = wx.statictext(self)
main_sizer.add(self.running_total, 0, wx.align_right)
feel free to download the full source from
github
or refer to the code in the previous section. the main differences here in regards to the text control is that you are no longer disabling it and you are binding it to an event:
wx.evt_text
.
let’s go ahead an write the
on_key()
method:
def on_key(self, event):
if self.on_key_called:
self.on_key_called = false
return
key = event.getstring()
self.on_key_called = true
if key in self.whitelist:
self.update_equation(key)
here you check to see whether the
self.on_key_called
flag is
true
. if it is, we set it back to
false
and "return" early. the reason for this is that when you use your mouse to click a button, it will cause
evt_text
to fire. the
update_equation()
method will get the contents of the text control which will be the key we just pressed and add the key back to itself, resulting in a double value. this is one way to work around that issue.
you will also note that to get the key that was pressed, you can call the
event
object’s
getstring()
method. then you will check to see if that key is in the white list. if it is, you will update the equation.
the next method you will need to update is
update_equation()
:
def update_equation(self, text):
operators = ['/', '*', '-', '+']
current_equation = self.solution.getvalue()
if text not in operators:
if self.last_button_pressed in operators:
self.solution.setvalue(current_equation + ' ' + text)
elif self.empty and current_equation:
# the solution is not empty
self.empty = false
else:
self.solution.setvalue(current_equation + text)
elif text in operators and current_equation is not '' \
and self.last_button_pressed not in operators:
self.solution.setvalue(current_equation + ' ' + text)
self.last_button_pressed = text
self.solution.setinsertionpoint(-1)
for item in operators:
if item in self.solution.getvalue():
self.update_solution()
break
here you add a new
elif
that checks if the
self.empty
flag is set and if the
current_equation
has anything in it. in other words, if it is supposed to be empty and it’s not, then we set the flag to
false
because it’s not empty. this prevents a duplicate value when the keyboard key is pressed. so basically, you need two flags to deal with duplicate values that can be caused because you decided to allow users to use their keyboard.
the other change to this method is to add a call to
setinsertionpoint()
on your text control, which will put the insertion point at the end of the text control after each update.
the last required change to the panel class happens in the
on_clear()
method:
def on_clear(self, event):
self.solution.clear()
self.running_total.setlabel('')
self.empty = true
self.solution.setfocus()
this change was done by adding two new lines to the end of the method. the first is to reset
self.empty
back to
true
. the second is to call the text control’s
setfocus()
method so that the focus is reset to the text control after it has been cleared.
you could also add this
setfocus()
call to the end of the
on_calculate()
and the
on_total()
methods. this should keep the text control in focus at all times. feel free to play around with that on your own.
creating a better
eval()
now that you have looked at a couple of different methods of keeping the “evil”
eval()
under control, let’s take a few moments to learn how you can create a custom version of
eval()
on your own. python comes with a couple of handy built-in modules called
ast
and
operator
. the
ast
module is an acronym that stands for “abstract syntax trees” and is used “for processing trees of the python abstract syntax grammar” according to the documentation. you can think of it as a data structure that is a representation of code. you can use the
ast
module to create a compiler in python.
the
operator
module is a set of functions that correspond to python’s operators. a good example would be
operator.add(x, y)
which is equivalent to the expression
x+y
. you can use this module along with the
ast
module to create a limited version of
eval()
.
let’s find out how:
import ast
import operator
allowed_operators = {ast.add: operator.add, ast.sub: operator.sub,
ast.mult: operator.mul, ast.div: operator.truediv}
def noeval(expression):
if isinstance(expression, ast.num):
return expression.n
elif isinstance(expression, ast.binop):
print('operator: {}'.format(expression.op))
print('left operand: {}'.format(expression.left))
print('right operand: {}'.format(expression.right))
op = allowed_operators.get(type(expression.op))
if op:
return op(noeval(expression.left),
noeval(expression.right))
else:
print('this statement will be ignored')
if __name__ == '__main__':
print(ast.parse('1+4', mode='eval').body)
print(noeval(ast.parse('1+4', mode='eval').body))
print(noeval(ast.parse('1**4', mode='eval').body))
print(noeval(ast.parse("__import__('os').remove('path/to/file')", mode='eval').body))
here you create a dictionary of allowed operators. you map
ast.add
to
operator.add
, etc. then you create a function called
noeval
that accepts an
ast
object. if the expression is just a number, you return it.
- the left part of the expression
- the operator
- the right hand of the expression
what this code does when it finds a
binop
object is that it then attempts to get the type of
ast
operation. if it is one that is in our
allowed_operators
dictionary, then you call the mapped function with the left and right parts of the expression and return the result.
finally, if the expression is not a number or one of the approved operators, then you just ignore it. try playing around with this example a bit with various strings and expressions to see how it works.
once you are done playing with this example, let’s integrate it into your calculator code. for this version of the code, you can call the python script
wxcalculator_no_eval.py
. the top part of your new file should look like this:
# wxcalculator_no_eval.py
import ast
import operator
import wx
class calcpanel(wx.panel):
def __init__(self, parent):
super().__init__(parent)
self.last_button_pressed = none
self.create_ui()
self.allowed_operators = {
ast.add: operator.add, ast.sub: operator.sub,
ast.mult: operator.mul, ast.div: operator.truediv}
the main differences here is that you now have a couple of new imports (i.e. ast and operator) and you will need to add a python dictionary called
self.allowed_operators
. next, you will want to create a new method called
no
:
eval()
def noeval(self, expression):
if isinstance(expression, ast.num):
return expression.n
elif isinstance(expression, ast.binop):
return self.allowed_operators[
type(expression.op)](self.noeval(expression.left),
self.noeval(expression.right))
return ''
this method is pretty much exactly the same as the function you created in the other script. it has been modified slightly to call the correct class methods and attributes, however. the other change you will need to make is in the
update_solution()
method:
def update_solution(self):
try:
expression = ast.parse(self.solution.getvalue(),
mode='eval').body
current_solution = str(self.noeval(expression))
self.running_total.setlabel(current_solution)
self.layout()
return current_solution
except zerodivisionerror:
self.solution.setvalue('zerodivisionerror')
except:
pass
now the calculator code will use your custom
eval()
method and keep you protected from the potential harmfulness of
eval()
. the code that is in github has the added protection of only allowing the user to use the onscreen ui to modify the contents of the text control. however, you can easily change it to enable the text control and try out this code without worrying about
eval()
causing you any harm.
wrapping up
in this chapter you learned several different approaches to creating a calculator using wxpython. you also learned a little bit about the pros and cons of using python’s built-in
eval()
function. finally, you learned that you can use python’s
ast
and
operator
modules to create a finely-grained version of
eval()
that is safe for you to use. of course, since you are controlling all input into
eval()
, you can also control the real version quite easily though your ui that you generate with wxpython.
take some time and play around with the examples in this article. there are many enhancements that could be made to make this application even better. when you find bugs or missing features, challenge yourself to try to fix or add them.
download the source
the source code for this article can be found on github . this article is based on one of the chapters from my book, creating gui applications with wxpython .
Published at DZone with permission of Mike Driscoll, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments