Reputation: 11
I have no idea of how to solve my problem i have a code that looks like this:
def f(x):
x=x.get()
y=x**2
z=x-1
Mylist=[]
x=Entry(master)
cmd=lambda x=x : f(x)
Button(master, text="Ok", command=cmd).pack()
What i want to do is something like
Mylist.append([y,z])
In order to use my results somewhere else in my program
Also i know that i could use a class but teachers don't want us to use class for that project...
Do you have any idea ?
Upvotes: 1
Views: 3597
Reputation: 385810
The whole point of attaching a command to a button is to implement the answer to the question "what do I want to happen when I click the button?". In your case, the answer is "I want it to a) get the value from an entry widget, b) calculate a new value, and c) append it to a list".
So, write a function that does that, and then call that function from your button. In this case you don't need lambda since you have a 1:1 relationship between the button and entry widget. There's nothing wrong with lambda per se, but in this case it adds complexity without providing any value so I recommend not using it. By not using lambda, the code will be easier to debug and maintain over time since it's hard to set breakpoints or add additional functionality inside a lambda.
For example:
def f(x):
y=x**2
z=x-1
def do_calculation():
x_value = float(x.get())
result = f(x_value)
my_list.append(result)
...
tk.Button(..., command=do_calculation)
Upvotes: 2
Reputation: 142631
Use append(f(x))
in lambda
and return [y,z]
in f(x)
. And you have to convert string from Entry
into int
or float
.
import tkinter as tk
# --- functions ---
def f(x):
x = int(x.get()) # convert string to int (or float)
y = x**2
z = x-1
return [y, z]
# --- main ---
my_list = []
master = tk.Tk()
e = tk.Entry(master)
e.pack()
cmd = lambda x=e:my_list.append(f(x))
tk.Button(master, text="Ok", command=cmd).pack()
master.mainloop()
print(my_list)
You can convert x
in lambda and then f(x)
could do only math calculations
EDIT: corrected version as @TadhgMcDonald-Jensen noted in the comment.
def f(x):
return [x**2, x-1]
#cmd = lambda x=int(e.get()):my_list.append(f(x)) # wrong version
cmd = lambda:my_list.append(f(int(e.get()))) # correect version
Upvotes: 1
Reputation: 49803
You know clicking the button will execute cmd
, so put whatever you want done (including appending to a list) in there. Note that this would mean either changing cmd
to not be a lambda
, or adding this functionality to f
(or something even more esoteric).
Upvotes: 0