1

I'm new in python programming and I'm having some issues in developing a specific part of my GUI with Tkinter.

What I'm trying to do is, a space where the user could enter (type) his math equation and the software make the calculation with the variables previously calculated.

I've found a lot of calculators for Tkinter, but none of then is what I'm looking for. And I don't have much experience with classes definitions.

I made this simple layout to explain better what I want to do:

import tkinter as tk

root = tk.Tk()

Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.pack()

thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.pack()

elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.pack()

applybutton = tk.Button(root, text = "Calculate")
applybutton.pack()

root.mainloop()

This simple code for Python 3 have 3 Entry spaces

1st) If...

2nd Then...

3rd) Else...

So, the user will enter with his conditional expression and the software will do the job. In my mind, another important thing is if the user left the "if" space in blank, he will just type his expression inside "Then..." Entry and press the button "calculate" or build all expression with the statements.

If someone could give some ideas about how and what to do....

(without classes, if it is possible)

I'l give some situations for exemplification 1st using statements:

var = the variable previously calculated and stored in the script 

out = output 

if var >= 10 

then out = 4 

else out = 2 

2nd Without using statement the user will type in "Then" Entry the expression that he want to calculate and that would be:

Then: Out = (((var)**2) +(2*var))**(1/2) 

Again, it's just for exemplification...I don't need this specific layout. If anyone has an idea how to construct it better, is welcome.

Thanks all.

Mike - SMT
  • 14,784
  • 4
  • 35
  • 79
GabrielBR
  • 25
  • 1
  • 6
  • Can you give some examples of your if-then-else expressions? – scotty3785 Jul 25 '17 at 11:06
  • of course! I'l give some situations 1st) using statments var = the variable previously calculated and stored in the script out = output if var >=10 then out = 4 else out = 2 2nd) Without useing statement the user will type in "Then" Entry the expression that he want to calculate and that would be Then: Out = (((var)**2) +(2*var))**(1/2) Again, it's just for exemplification...I don't need this specific layout. – GabrielBR Jul 25 '17 at 12:14
  • So why exactly do you need the if-then-else fields? As far as I can tell all complex calculators use a single entry field. – Mike - SMT Jul 25 '17 at 14:51
  • Yes, you're right! Could be that too. My issue is to make that value from a Entry (which is a string) and make it be a function and calculate the equation. – GabrielBR Jul 25 '17 at 14:55

2 Answers2

2

Here is a simple version of what you are trying to do.

We need to use the eval built in function to evaluate the math of a string.

We should also write our code with some error handling as there is a very good change a user will type a formula wrong and the eval statement will fail.

For more information on eval and exec take a look at this post here. I think it does a good job of explaining the two.

Here is what it would look like:

import tkinter as tk

root = tk.Tk()

math_label = tk.Label(root, text = "Type formula and press the Calculate button.")
math_label.pack()
math_entry = tk.Entry(root)
math_entry.pack()
result_label = tk.Label(root, text = "Results: ")
result_label.pack(side = "bottom")

def perform_calc():
    global result_label
    try:
        result = eval(math_entry.get())
        result_label.config(text = "Results: {}".format(result))
    except:
        result_label.config(text = "Bad formula, try again.")


applybutton = tk.Button(root, text = "Calculate", command = perform_calc)
applybutton.pack()

root.mainloop()
Mike - SMT
  • 14,784
  • 4
  • 35
  • 79
2

The first answer gets at the right thought, but it can also be matched a little more explicitly to the example you gave, in case you want to take this a little further.

Basically you want to use the eval statement to test your conditional, and then use the exec statement to run your python code blocks. You have to pass in the globals() argument in order to make sure your exec functions modify the correct variables in this case

See below:

import tkinter as tk
from tkinter import messagebox

var = 10
out = 0

def calculate():
    global out

    try:
        if eval(IfEntry.get()):
            exec(thenEntry.get(), globals())
        else:
            exec(elseEntry.get(), globals())
        messagebox.showinfo(title="Calculation", message="out: " + str(out))
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        msg = traceback.format_exception(exc_type, exc_value, exc_traceback)
        messagebox.showinfo("Bad Entry", message=msg)            

root = tk.Tk()

Iflabel = tk.Label(root, text = "If...")
Iflabel.pack()
IfEntry = tk.Entry(root)
IfEntry.insert(0, "var >= 10")
IfEntry.pack()

thenlabel = tk.Label(root, text = "Then...")
thenEntry = tk.Entry(root)
thenlabel.pack()
thenEntry.insert(0, "out = 4")
thenEntry.pack()

elselabel = tk.Label(root, text = "else..")
elseEntry = tk.Entry(root)
elselabel.pack()
elseEntry.insert(0, "out = 2")
elseEntry.pack()

applybutton = tk.Button(root, command=calculate, text = "Calculate")
applybutton.pack()


applybutton.focus_displayof

root.mainloop()
Vince W.
  • 3,561
  • 3
  • 31
  • 59
  • Good work on this. My answer was more in response to one of the OPs comments but I like you answer more :) – Mike - SMT Jul 25 '17 at 15:26
  • thanks, probably good to point out that there should be some form of error handling to go along with this as you have in your example. – Vince W. Jul 25 '17 at 15:29
  • Ya there is a good chance for a bad formula typed due to user error so error handling is a good idea here. – Mike - SMT Jul 25 '17 at 15:31