Creating a Desktop Calculator with wxPython
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 discourage the user of eval()
.
Let's find out why.
Keep reading with a 7-day free trial
Subscribe to The Python Papers to keep reading this post and get 7 days of free access to the full post archives.