How to make expressions in Tkinter Python - python

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.

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

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

Related

Tkinter Passing StringVar.get through command lambda gives initial value

Okay, so I am trying to make a menu system using Tkinter and am trying to save the string value of the drop down menu to a class variable. I have code to handle that part, but the problem comes with getting that string value to the function I have written. I know that it isn't my function that is the problem as I am using the print function for my example below.
import tkinter as tk
from enum import Enum
class CustomEnum(Enum):
Option1 = 'Option1'
Option2 = 'Option2'
class window():
def __init__(self, root):
self.value = CustomEnum.Option1
test = tk.StringVar()
test.set(self.value.value)
tk.OptionMenu(root, test, *[e.value for e in CustomEnum], command = lambda
content = test.get() : print(content)).pack()
tk.Button(root, text="Save",
command = lambda content = test.get() : print(content)).pack()
root = tk.Tk()
test = window(root)
root.mainloop()
If you run this code, it'll constantly print "Option 1" despite what option you chose or if you add or remove elements (aside from removing Option 1).
The problem lies in this line
tk.Button(root, text="Save",
command = lambda content = test.get() : print(content)).pack()
You are assigning content the value of test.get() which was at that instant (Option1) and it continues to be so unchanged.
Since you want the current value of test.get(), you would have to do this
command = lambda: print(test.get())).pack()
Also, I believe you have misspelt customEnum instead of CustomEnum.

Why Does My Tkinter Calculator Only Return Zero?

I am fairly new to Tkinter and I'm trying to code a simple calculator. My problem is no matter what integers I provide the entry widget the sum always returns as zero. Any help would be greatly appreciated.
I have tried making the variables into global variables giving me the same result. I have also tried converting the entry from a StringVar() to int, but this results in a invalid literal error.
(ValueError: invalid literal for int() with base 10: '')
def addRes():
ni1 = int(na1.get())
ni2 = int(na2.get())
result = ni1 + ni2
resAdd = str(result)
Radd = Tk()
Radd.geometry("50x50")
addL = Label(Radd, text= resAdd).pack()
nEadd = Tk()
nEadd.geometry("200x200")
na1 = IntVar()
na2 = IntVar()
numVal1 = Entry(nEadd).place(x=20,y=10)
plusL = Label(nEadd, text= "+").place(x=20,y=30)
numVal2 = Entry(nEadd).place(x=20,y=50)
addResult = partial(addRes)
numSubmit = Button(nEadd, text= "Submit", command = addResult).place(x=40,y=70)
Although you create two IntVars, you don't associate them with an entry so they never change.
You need to change the entries to this:
numVal1 = Entry(nEadd, textvariable=na1).place(x=20,y=10)
numVal2 = Entry(nEadd, textvariable=na2).place(x=20,y=50)
Also, you should not be creating more than one instance of Tk. If you need another window, use Toplevel

Retrieving value from Tkinter combobox

Eventually I want to use the values in the comboboxes as parameters in other functions, but I think if I can just get them to print for now, that will be enough to build off of. Here's what I have so far.
import tkinter as tk
from tkinter import ttk
import time
def ok():
betType = betTypeVar.get()
season = seasonVar.get()
print(betType, season)
def CreateSimPreviousSeasonWindow():
prevSeasonWindow = tk.Tk()
#============= Bet Type Input =============#
betTypeVar = tk.StringVar()
betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
betTypeChosen = ttk.Combobox(prevSeasonWindow, values=['Moneyline','Total'])
betTypeChosen.grid(row=0, column=1)
seasonVar = tk.StringVar()
seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
seasonChosen.grid(row=1,column=1)
button = tk.Button(prevSeasonWindow, text='OK', command=ok)
button.grid(row=2,column=0)
prevSeasonWindow.mainloop()
This gives me
File "C:[directory...]", line 6, in ok
betType = betTypeVar.get()
NameError: name 'betTypeVar' is not defined
To me it looks pretty obvious that this error is because ok() doesn't have any parameters passed to it, so it has no idea what 'betTypeVar' is, but all the tutorials I've read do it this way, so I'm missing something. If I try actually passing ok() the arguments, it still doesn't work.
There are two things to fix in your code. First let's focus on CreateSimPreviousSeasonWindow:
betTypeVar = tk.StringVar()
seasonVar = tk.StringVar()
You defined two StringVar but you actually never used it or linked them to your combobox object. The correct way is to set them as a textvaraible:
betTypeChosen = ttk.Combobox(prevSeasonWindow, textvariable=betTypeVar, values=['Moneyline','Total'])
seasonChosen = ttk.Combobox(prevSeasonWindow, textvariable=seasonVar, values=['2018', '2017'])
Next, NameError: name 'betTypeVar' is not defined is due to your variables being local variables. You are trying to access the same variable across different functions. To pass them around, you need to declare global:
def ok():
global betTypeVar, seasonVar
betType = betTypeVar.get()
season = seasonVar.get()
print(betType, season)
def CreateSimPreviousSeasonWindow():
global betTypeVar, seasonVar
...
Also I want to point out that if you just want to retrieve the values of the combobox, you don't really need to create two StringVar. Just combobox.get() already works good enough.
import tkinter as tk
from tkinter import ttk
import time
def ok():
global betTypeChosen, seasonChosen
print (betTypeChosen.get(), seasonChosen.get())
def CreateSimPreviousSeasonWindow():
global betTypeChosen,seasonChosen
prevSeasonWindow = tk.Tk()
#============= Bet Type Input =============#
betTypeLabel = tk.Label(prevSeasonWindow, text="Bet type:").grid(row=0,column=0)
betTypeChosen = ttk.Combobox(prevSeasonWindow,values=['Moneyline','Total'])
betTypeChosen.grid(row=0, column=1)
seasonLabel = tk.Label(prevSeasonWindow, text='Season:').grid(row=1, column=0)
seasonChosen = ttk.Combobox(prevSeasonWindow, values=['2018', '2017'])
seasonChosen.grid(row=1,column=1)
button = tk.Button(prevSeasonWindow, text='OK', command=ok)
button.grid(row=2,column=0)
prevSeasonWindow.mainloop()
CreateSimPreviousSeasonWindow()

Possible to remove/deactivate variables from an executed line?

Is it possible to remove/deactivate variables from a line of code once it has been executed? If not, what are my other options? I wrote a code here to demonstrate what I mean:
from Tkinter import *
root = Tk()
ent_var1 = StringVar()
ent_var2 = StringVar()
ent_var3 = StringVar()
cbtn_var1 = BooleanVar()
cbtn_var2 = BooleanVar()
cbtn_var3 = BooleanVar()
ent1 = Entry(textvariable=ent_var1).pack()
ent2 = Entry(textvariable=ent_var2).pack()
ent3 = Entry(textvariable=ent_var3).pack()
cbtn1 = Checkbutton(text=1, variable=cbtn_var1).pack(side = LEFT)
cbtn2 = Checkbutton(text=2, variable=cbtn_var2).pack(side = LEFT)
cbtn3 = Checkbutton(text=3, variable=cbtn_var3).pack(side = LEFT)
# prints what was written in entires
def set_variables():
lbl1 = ent_var1.get()
lbl2 = ent_var2.get()
lbl3 = ent_var3.get()
print lbl1, lbl2, lbl3
return
# calls set_variables
btn1 = Button(root, text="Done!", command=set_variables).pack()
root.mainloop()
When you fill the entries and press "Done!", what was written is printed. But how do I make it so that when I press the checkboxes, the entry linked to it will not be printed the next the I press "Done!"? The checkbox with the text "1" should be linked with the first entry, and so on.
I came up with this:
def should_print():
global lbl_print
if cbtn1:
lbl_print += lbl1
if cbtn2:
lbl_print += lbl2
if cbtn3:
lbl_print += lbl3
But it would only print the values of my variables at that very moment, not the variables themselves (meaning I'd have to run this code every time a variable changes).
Thank you!
Your question is very hard to understand. I think what you want is for set_variables to only print the variables associated with a checked checkbox. If so, does the following do what you want?
def set_variables():
to_print = []
if cbtn_var1.get():
to_print.append(ent_var1.get())
if cbtn_var2.get():
to_print.append(ent_var2.get())
if cbtn_var3.get():
to_print.append(ent_var3.get())
print " ".join(to_print)
return
There are other ways to accomplish the same thing, but I'm guessing your main goal is to decide what to print based on which checkbuttons are checked. This does that, albeit in a rather ham-fisted manner.
Why don't you simply check in your set_variables function if each button is pressed? For example:
def set_variables():
if not cbtn_var1.get():
print ent_var1.get(),
if not cbtn_var2.get():
print ent_var2.get(),
if not cbtn_var3.get():
print ent_var3.get(),
print
The commas at the end of each print statement will cause it to not print a newline, which is taken care of by the print at the end. Also, this will make so that if the box is checked, the value they entered won't print. If you want it to print only if the box is checked, then remove the nots.
If you refactor your code a little bit, you can do the same thing with one line. First, add this line:
cbtn_var1 = BooleanVar()
cbtn_var2 = BooleanVar()
cbtn_var3 = BooleanVar()
buttonsAndValues = [(cbtn_var1,ent_var1), (cbtn_var2,ent_var2), (cbtn_var3,ent_var3)]
With the variables in a list, you can use a list comprehension in some Python magic:
def set_variables():
print ' '.join(value.get() for checked, value in buttonsAndValues if checked.get())
If you haven't seen list comprehensions before, I'd suggest you read up about them - they can be very handy.

Tkinter, saving functions to a list and then running them

I'm working on a GUI for a project in school. All the buttons that I have in my GUI are bound with functions that I have created. These functions call for already predefined functions. For some of the predefined functions, I need one or two arguments and I have solved that with entries. I type in the arguments in the right entries that are connected to the specific button and when I press the button, the function will run with the corresponding arguments.
The thing I want to do is to in some way when I press a button, the function should be saved to a list instead of being executed right away. And when I push the "run" button(a new button that I will create) everything in my list will be executed. I have been thinking about using a list box but I don't know exactly how they work or if its even possible to run a list box that contains a number of functions. Does someone have any ideas or solutions for me? Can I use the list box for this or is there something else that is better to use?
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.entry1 = IntVar()
self.entry2 = IntVar()
def do_something():
value1 = self.entry1.get()
value2 = self.entry2.get()
self.listbox.insert(END, "predefined_function(value1, value2)")
def run_listbox_contents():
pass
self.button = Button(frame, text="Move", command=lambda: do_something())
self.button.pack(side=TOP)
self.entry1.set("value1")
self.entry = Entry(frame, textvariable=self.entry1)
self.entry.pack(side=TOP)
self.entry2.set("value2")
self.entry = Entry(frame, textvariable=self.entry2)
self.entry.pack(side=TOP)
self.listbox = Listbox(master)
self.listbox.pack(side=TOP)
root = Tk()
app = App(root)
root.title("Mindstorms GUI")
root.geometry("800x1200")
root.mainloop()
root.destroy()
Just use a standard list.
something like this
def hest(txt):
print "hest: " +txt
def horse(txt):
print "horse: " + txt
funcList = []
funcList.append(hest)
funcList.append(horse)
for x in funcList:
x("Wow")
This outputs
hest: Wow
horse: Wow
Was this what you wanted?
If I were you, I wouldn't want to save functions to a list. I would suggest another solution for you.
I suppose you have heard of the principle of MVC (Model-View-Controller). In your case, the list box is a part of view, and the process that saves functions and then calls them at once is a part of controller. Separate them.
You might want to save and display any string in the list box to let the users know that the corresponding functions have been enlisted and ready to run. For example, save a string "Function1 aug1 aug2 aug3" or "Funtion2 aug1 aug2" or whatever you like as a handle of the corresponding function.
And for the controller part, write a function (let's say conductor()). It reads the handle strings from the list, parses them and calls the corresponding functions. Where you want to run the enlisted functions, there you just call conductor().
Update:
Due to your comment I understand that you are pretty new to program. Let me show you how to write a simplest parser with your given variable names.
def run_listbox():
to_do_list = #get the list of strings
for handle_string in to_do_list:
#Let's say you got
#handle_string = "Predfined_function1 value1 value2"
#by here
handle = handle_string.split(" ")
#Split the string by space, so you got
#handle = ["Predfined_function1", "value1", "value2"]
#by here
if handle[0] == "Predfined_function1":
Predfined_function1(handle[1], handle[2]) #Call Predfined_function1(value1, value2)
elif handle[0] == "Predfined_function2":
Predfined_function2(handle[1], handle[2])
#elif ...
#...
#elif ...
#...
#elif ...
#...
This is not a perfect parser, but I hope it could let you know what does a parser look like.

Categories