python Tkinter:将参数传递给函数 [英] python Tkinter: passing an argument to a function
问题描述
可以请任何人帮助我解决我的问题.我是 python 的新手,在以下情况下我不知道如何将参数传递给函数:在一个单独的文件 (sentiment_analysis) 中,我有一个字典和一个对象数组:
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)
我想我必须将标签 (p) 的值作为 onButtonPosObject() 函数的参数传递,我需要从 positiveSentiments 字典中为每个对象获取单词列表,但我得到像 [] 这样的空值.如有任何建议,我将不胜感激!
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!
推荐答案
你需要在 lambda 中捕获 p 的当前值:
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)
这篇关于python Tkinter:将参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!