0

I am making a python calculator with GUI for school.

I have got some basic code from the internet and I have to customize it by changing things around. So far I have added a DEL button, a ^2 button and a sqrt() button.

I now want that if I type in an equation on my keyboard, e.g. "2*4", and press Enter it will simulate as pressing the equals button. I am having trouble finding out how to get python to register me clicking the Enter and then give me an answer.

This is the code:

from __future__ import division
from math import *
from functools import partial
try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
class MyApp(tk.Tk):
    def __init__(self):
        # the root will be self
        tk.Tk.__init__(self)
        self.title("Magic")
        # use width x height + x_offset + y_offset (no spaces!)
        #self.geometry("300x150+150+50")
        # or set x, y position only
        self.geometry("+150+50")
        self.memory = 0
        self.create_widgets()
    def create_widgets(self):
        # this also shows the calculator's button layout
        btn_list = [
        '7',  '8',  '9',  '*',  'AC',
        '4',  '5',  '6',  '/',  'x²',
        '1',  '2',  '3',  '-',  '√x',
        '0',  '.',  '=',  '+',  'DEL' ]
        rel = 'ridge'
        # create all buttons with a loop
        r = 1
        c = 0
        for b in btn_list:
            # partial takes care of function and argument
            cmd = partial(self.calculate, b)
            tk.Button(self, text=b, width=5, relief=rel,
                command=cmd).grid(row=r, column=c)
            c += 1
            if c > 4:
                c = 0
                r += 1
        # use an Entry widget for an editable display
        self.entry = tk.Entry(self, width=37, bg="white")
        self.entry.grid(row=0, column=0, columnspan=5)

    def undo():
            new_string = whole_string[:-1]
            print(new_string)
            clear_all()
            display.insert(0, new_string)

    def calculate(self, key):
        if key == '=':
            # here comes the calculation part
            try:
                result = eval(self.entry.get())
                self.entry.insert(tk.END, " = " + str(result))
            except:
                self.entry.insert(tk.END, "")
        elif key == 'AC':
            self.entry.delete(0, tk.END)
        elif key == 'x²':
            self.entry.insert(tk.END, "**")
            # extract the result
        elif key == '√x':
            self.memory = self.entry.get()
            self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, "sqrt(")
            self.entry.insert(tk.END, self.memory)
            self.entry.insert(tk.END, ")")
        elif key == 'DEL':
            self.memory = self.entry.get()
            self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, self.memory[:-1])

        else:# previous calculation has been done, clear entry
            if '=' in self.entry.get():
                self.entry.delete(0, tk.END)
            self.entry.insert(tk.END, key)

app = MyApp()
app.mainloop()
Lafexlos
  • 7,618
  • 5
  • 38
  • 53
Dylan H
  • 1
  • 1

1 Answers1

1

You can use bind() to assign function to Entry which will be executed when you press Enter

Example:

import tkinter as tk

def on_return(event):
    print('keycode:', event.keycode)
    print('text in entry:', event.widget.get())

root = tk.Tk()

e = tk.Entry(root)
e.pack()
e.bind('<Return>', on_return)   # standard Enter
e.bind('<KP_Enter>', on_return) # KeyPad Enter

root.mainloop()

In your code it can be - for test

self.entry = tk.Entry(self, width=37, bg="white")
self.entry.grid(row=0, column=0, columnspan=5)

self.entry.bind('<Return>', lambda event:print("ENTER:", event.widget.get()))
self.entry.bind('<KP_Enter>', lambda event:print("ENTER:", event.widget.get()))

If you have class method def on_return(self, event): then

self.entry.bind('<Return>', self.on_return)
self.entry.bind('<KP_Enter>', self.on_return)

  1. Events and Bindings

  2. Key names

furas
  • 134,197
  • 12
  • 106
  • 148
  • Thanks for that. I might see if i can familiarize myself with python a little bit more and try making my own calculator. It might help me understand everything a bit better. – Dylan H Oct 19 '16 at 09:12
  • After adding the `self.entry.bind('', lambda event:print("ENTER:", event.widget.get()))` I can confirm it now respond to my key press. – Dylan H Oct 19 '16 at 09:20