我试图通过将变量传递给函数来使Optionmenu-Widget工作 当用户单击菜单中的选项时,我需要传递两个变量。
self.frameX = Frame(self.frameTwo, background="red", width= 370, height=35)
self.frameX.pack_propagate(0)
self.frameX.pack(side=TOP)
self.names = [1,2,3,4,5]
#Just for demonstration, some random number i
#should be saved and passed onchange optionmenu.
i = random.randint(0, 10)
self.var = StringVar()
self.var.set("Numbers")
#When the user selects an option, this function should
#pass i and the variable, which is what the user selected to the callback function.
self.var.trace("w", lambda i=i: self.callback(i, self.var.get()))
self.options = OptionMenu(self.frameX, self.var, *self.names)
self.options.place(x=180, y=5)
self.options.pack()
self.frameX.pack()
def callback(self, n, g):
print(n)
print(g)
如果有人能帮助我解决这个问题,那将会很棒并且很受欢迎。
答案 0 :(得分:1)
如果我理解正确你想要做这样的事情:
import random
from Tkinter import *
def callback(sv, i):
print sv.get() + str(i);
master = Tk()
i = random.randint(0, 10)
variable = StringVar(master)
variable.set("one") # default value
variable.trace("w", lambda name, index, mode, sv=variable: callback(sv, i))
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
正如您所看到的,我传递了stringVar本身,因此我可以在回调中调用get()
和其他函数
更改OptionsMenu-Value打印,例如
>>two6
>>one6
>>three6