Reputation: 119
Can please anyone help me with my problem. I am new to python and I can not get how to pass an argument to a function in the following case: In a separate file (sentiment_analysis) I have a dictionary and an array of objects:
positiveSentiments = dict() // here are some words related to each of the object
objects = ['Google', 'Apple', 'Motorola']
I need to display positive sentiments of each object:
def onButtonPosObject(p):
for key in sentiment_analysis.positiveSentiments.keys():
if key == p:
text.insert(END, sentiment_analysis.positiveSentiments[key])
submenu = Menu(text, tearoff=0)
for p in sentiment_analysis.objects:
submenu.add_command(label=p, command = lambda : onButtonPosObject(p), underline=0)
textmenu.add_cascade(label='Display positive sentiments', menu=submenu, underline=0)
I think I have to pass a value of label (p) as a parameter of onButtonPosObject() function and I need to get a list of words from positiveSentiments dictionary for every object but I get empty value like []. I would be very grateful for any recommendations!
Upvotes: 3
Views: 2197
Reputation: 386352
You need to capture the current value of p in the lambda:
submenu.add_command(label=p, command = lambda p=p: onButtonPosObject(p), underline=0)
Upvotes: 5
Reputation: 3399
I'm guessing what's happening is that your positiveSentiments['Motorola'] list is empty. I'd add a print statement in that 'for p in sentiment_analysis.objects' loop to see whats going on. When you use a lambda command in a loop like that, you end up setting the command for each menu item to pass the same value for p (it will be the final value of p) when they call onButtonPosObject.
You need to save the variable to a name local to each lambda, and pass that as the argument (it looks messy, I know): lambda x=p: onButtonPosObject(x)
. Try it and see what you get.
Upvotes: 0