How to make expressions in Tkinter Python

人盡茶涼 提交于 2019-12-24 10:56:44

问题


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.


回答1:


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()



回答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()


来源:https://stackoverflow.com/questions/45300287/how-to-make-expressions-in-tkinter-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!