python Tkinter:将参数传递给函数

python Tkinter:将参数传递给函数,python,tkinter,Python,Tkinter,请任何人帮我解决我的问题。我是python新手,在以下情况下无法了解如何将参数传递给函数: 在一个单独的文件(情绪分析)中,我有一个字典和一组对象: positiveSentiments = dict() // here are some words related to each of the object objects = ['Google', 'Apple', 'Motorola'] 我需要展示每个对象的积极情绪: def onButtonPosObject(p): for key i

请任何人帮我解决我的问题。我是python新手,在以下情况下无法了解如何将参数传递给函数: 在一个单独的文件(情绪分析)中,我有一个字典和一组对象:

positiveSentiments = dict() // here are some words related to each of the object
objects = ['Google', 'Apple', 'Motorola']
我需要展示每个对象的积极情绪:

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)
我想我必须传递一个label(p)的值作为onButtonPosObject()函数的参数,我需要从PositiveEntities字典中获取每个对象的单词列表,但我得到的是像[]这样的空值。
如有任何建议,我将不胜感激

我猜现在发生的事情是你的积极情绪['Motorola']列表是空的。我会在“情感分析中的p.objects”循环中添加一个print语句,看看发生了什么。当您在这样的循环中使用lambda命令时,您最终会将每个菜单项的命令设置为在调用onButtonPosObject时为p传递相同的值(它将是p的最终值)


您需要将变量保存为每个lambda的本地名称,并将其作为参数传递(我知道它看起来很混乱):
lambda x=p:onButtonPosObject(x)
。尝试一下,看看你得到了什么。

你需要捕获lambda中p的当前值:

submenu.add_command(label=p, command = lambda p=p: onButtonPosObject(p), underline=0)