Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Tutorials listed in this section have not been reviewed nor are affliated by Code Forum. It is the sole responsbility of the authour to properly maintain and ensure information is accurate.

Python Simple Tkinter Calculator Part 3 (Build methods and bind buttons)

Simple Tkinter Calculator Part 3
In part3 we will:
  • Create methods in our Controller class
  • Bind the buttons to the methods
  • Create a simple validation

Create methods

Python:
    def valid_input(self,arg):
        ''' Method for validating input '''
        if arg.isalpha() or arg == '=':
            return False
        else:
            return True
 
    def clear(self, event):
        ''' Method for clearing the entry field '''
        self.window.entry.delete(0, 'end')

    def insert(self, var):
        ''' Method for inserting numbers in the entry field '''
        self.window.entry.insert('end', var)

    def calculate(self, event):
        ''' Method for doing calculations '''

        # Get the values of the entry field
        values = self.window.entry.get()

        # Do and get the calculations from the entry field using eval
        # It is reccommended not to use eval but, for our purpose
        # it will be fine
        result = eval(values)

        # Checking if our number is a float and is a whole number.
        # If it is a whole number it will remove the .0
        # else return the number as is
        if isinstance(result, float):
            result = Decimal(result).normalize()
        else:
            result = result

        # Clear the entry field and insert the calculation back into the entry field
        self.window.entry.delete(0, 'end')
        self.window.entry.insert('end', result)

Create the button commands, binds and validation
Python:
        # Create commands for our buttons
        for btn in self.window.btns:
            # If the buttons are not = or clear - give the insert command
            if btn['text'] not in ['Clear', '=']:
                btn['command'] = lambda var=btn['text']: self.insert(var)
            elif btn['text'] == 'Clear':
                # If the button is the clear button - clear the field
                btn['command'] = lambda: self.clear(None)
            else:
                # Else calculate
                btn['command'] = lambda var=btn['text']: self.calculate(var)

        # Bind keys to perform some actions
        self.window.parent.bind('<Return>', lambda var=btn['text']: self.calculate(var))
        self.window.parent.bind('<KP_Enter>', lambda var=btn['text']: self.calculate(var))
        self.window.parent.bind('<Escape>', self.clear)

        # Validate input - Needs to be numbers or *,+,/,-
        valid = self.window.parent.register(self.valid_input)
        self.window.entry.configure(validate='key', validatecommand=(valid, '%S'))
 
Back
Top Bottom