A GUI Python Calculator

Click on image to download the code.

Python Calculator

Here’s a little calculator I wrote.

I’ve recently had a look at this and fixed the divide by zero bug.

The links now point to updated code on github.

It you want to look at the code and/try it out, just click on the picture. Or click here.

If you find any bugs, let me know.

Read on if you want to know how the code works.

The program begins by importing tkinter, to handle the GUI. Straight after that we set up a “class” called “Calc()”. In some of the programs we’ve looked at so far, we have been using pre-defined “classes” and, therefore, the Object Orientated approach to programming. What’s different this time is that we are creating a class from scratch.

The first “method” that we create for this class of objects is a “constructor”. This section of code is run automatically whenever and instance of “Calc() is create. The object has some variables associated with it. Total is a running total of the sums we have done so far – so we set it to zero initially. “self.current” is a string in which we hold the numbers that are being entered via the GUI. Then we have three “flags”. I’m not sure if this is the most effective way to do this, but it seems to work okay. The “new_num” flag is set to true if the calculator is expecting a new number (eg after the user has pressed “+” etc.) There’s also a flag for “op_pending” which tells if there is still a calculation to do. The flag “self.eq_flag” keeps a record of whether equals has just been pressed. I needed these flags to make the calculator work as expected. For instance, you can press “equals” when there is no operation pending, and the number will stay the same. You can press an operator after “equals” and that action will be done to the current total. Or you can start a new number after pressing equals and the previous target is discarded.

Each instance of the class I am creating will have these variables, and also some “methods”.  Methods look just like functions. This one controls how the calculator responds to a number being pressed. First it takes the text from the box. If the new_num flag is set to “True”, it ignores what was in the text box and starts a new number with the button-press. Of course it then sets the “new_num” flag to false, so that we can add more digits to this number.

If we are not looking for a new number, it will continue adding the digits we have pressed onto the “self_current” string (at this point we are treating whatever is input as a String). The method also checks that the used hasn’t tried to have 2 decimal point symbols. Only the first one will actually be accepted.

The method ends by deleting everything in the text-box and printing the “self_current” string out again.

Now we deal with the method that gets called when we press equals. This is a very simple method! If there is an operation pending (ie. a sum to do), then we do the sum. Otherwise, pressing equals has no effect

Next comes the “do_sum” method. This starts off by converting the string in “self.current” to a floating point number. It then does the operation that is stored in “self.op”, performing it on “self.total” and “self.current”. Then it displays the result in the text box and sets the new_num flag to True.

This method defines what happens if one of the “operation” buttons on the calculator is pressed. If we have an operation “pending”, the we work that out first. Otherwise, we check that the total variable holds the correct total and set the op_pending and new_num flags to true, so that we are ready to find out which value the user wants this operation applied to.

The next three methods sort out some simple matters. The cancel, all_cancel and “+/-” buttons. As you can see, all_cancel is the same as cancel, but with the additional zeroing of self.total. And the plus / minus button just inverts the sign of whatever is in the text-box at that moment.

And that’s it for the workings of the calculator. The rest of the program just sets up the GUI. I am not going to spend too long on this, except to show you how I  made some of my buttons with a loop.


By the way, if you haven’t seen “lambda:” before, this is a really useful thing. Usually, when you specify a function in the command part of a button’s creation, you leave the brackets off. If you leave them on, the program will behave as if the button has been pressed, even when it has not! Lambda lets you get around this, which is of course essential if you want to pass some parameter to that function.

Here’s the loop that makes the buttons 1-9.





So first I created a little string with my numbers in the order they appear on the buttons on a number pad. Then I use j and k to iterate over all the positions in my grid in which I want a button. I use my version of the Button class which will allow me to use my built-in command-setting method.

I’m not going to write any more than that. You can download the code if you want to see the whole thing.

Please let me know if you spot any mistakes or ways to improve this.



23 Responses to “A GUI Python Calculator”

  1. Juan Antonio Larrreina Says:

    How can I get the ‘tkinter’ module?

  2. antiloquax Says:

    Usually it is there in a standard installation. Does idle work on your system? If so, you have it. If you are using python 2.x, try:
    import Tkinter.

  3. wasmester Says:

    im getting

    attribute error type object ‘ calc’ has no attribute tk

  4. Janette Says:

    Great post.

  5. Alfred George Says:

    can you provide all code… please

  6. antiloquax Says:

    Yes, I’ll post a link later today.

  7. Peter mwale Says:

    Its really cool

  8. Benny_James Says:

    Division by zero causes a crash.
    Try putting in some exception handling:

    if self.op == “divide”:
    self.total /= self.current
    except ZeroDivisionError:
    self.total = ‘Error’

    Otherwise an overall good job. Keep It up.

  9. Benny_James Says:

    sorry my comment’s tabs did not get carried over

  10. egege Says:


  11. egege Says:

    thanks much lot yay

  12. Amira Says:

    The code didn’t work for me

  13. Sudhakar K Says:

    Really a good way to start GUI. Thank you.
    I tried in python 3.2 (idle).

  14. Matt Mccarthy Says:

    For fellow python noobs, if you’re getting tkinter mod error, Capitalize the ‘t’ in ‘tkinter’ in the import directive. should be:
    from Tkinter import *

  15. Jerald Says:

    Wow! Finally I got a weblog from where I be capable of actually
    obtain helpful information regarding my study and knowledge.

  16. NeptuneX Says:

    to import in python 2.7
    import Tkinter
    to import in python 3 or above
    import tkinter
    hope this works.. 🙂

  17. harikeshkumar59 Says:

    Reblogged this on Harikesh.

  18. prashant khati Says:

    i am write the correct code as u given but line number 13 gives the error of ‘unident does not match ant outer indentation level’
    so please tell mi meaning of this error
    fast i am working and today is reporting day so plz tell mi immeditely

  19. Sarang Says:

    Wonderful. Gonna try this now!

  20. Sarang Says:

    Woooohooooo! Lovely calc developers!

  21. Felix Welch Says:

    where is the download link

  22. antiloquax Says:

    Sorry about the broken link.

  23. antiloquax Says:

    I’ve now fixed the divide-by-zero and updated the links to point at my github.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: