简体   繁体   English

python Tkinter:将参数传递给函数

[英]python Tkinter: passing an argument to a function

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: 我是python的新手,在以下情况下无法获取如何将参数传递给函数的信息:在一个单独的文件(sentiment_analysis)中,我有一个字典和一个对象数组:

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 []. 我想我必须将标签(p)的值作为onButtonPosObject()函数的参数传递,并且我需要从positiveSentiments字典中为每个对象获取单词列表,但我会得到[]这样的空值。 I would be very grateful for any recommendations! 如有任何建议,我将不胜感激!

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

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

I'm guessing what's happening is that your positiveSentiments['Motorola'] list is empty. 我猜发生了什么事,您的positiveSentiments ['Motorola']列表为空。 I'd add a print statement in that 'for p in sentiment_analysis.objects' loop to see whats going on. 我会在“ sentiment_analysis.objects”循环中的“ for p”中添加一条打印语句,以查看发生了什么情况。 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. 当在这样的循环中使用lambda命令时,最终会为每个菜单项设置命令,以在它们调用onButtonPosObject时为p传递相同的值(它将是p的最终值)。

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) . 您需要将变量保存为每个lambda的本地名称,并将其作为参数传递(我知道这看起来很乱): lambda x=p: onButtonPosObject(x) Try it and see what you get. 尝试一下,看看会得到什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM