如何从组合框中同时获取并传递选定的值到函数

时间:2014-08-27 08:55:42

标签: python-2.7 tkinter ttk

我想从组合框中获取所选值,同时我必须将该值传递给其他调用函数,该怎么做?我写的代码不足以达到这个要求,有人请​​帮助我。我熟悉C#和其他语言的SelectedIndexChanged!与Tkinter python类似吗?

def fill_Combo(self):
    combo1= ttk.Combobox(frame1,height=1, width=20)
    combo1['values'] = ("AA","BB","CC","DD","EE")
    combo1.current(0)
    combo1.pack()                  
    combo1.place(x=5, y = 75)
    var_Selected=combo1.current()
    combo1.bind("<<ComboboxSelected>>",select_Combo(var_Selected))


def select_Combo(self,var_Selected):
    print "The user selected value now is:"
    print  var_Selected

1 个答案:

答案 0 :(得分:0)

目前,var_Selected始终为0,因为您在创建组合框时将当前设置为0,并且只将var_Selected设置为此值。您需要做的是在combo1.current()执行时获取select_Combo。您可以将combo1重命名为self.combo1,然后通过自动自动传递给select_Combo。然后你可以获得当前值并用它做任何你想做的事情。 并且不要同时使用packplace,选择一个。

示例:

from Tkinter import *
import ttk

class app():

    def __init__(self):
        self.root = Tk()
        self.fill_Combo()
        self.root.mainloop()

    def fill_Combo(self):
        self.combo1= ttk.Combobox(self.root,height=1, width=20)
        self.combo1['values'] = ("AA","BB","CC","DD","EE")
        self.combo1.current(0)              
        self.combo1.place(x=5, y = 75)
        self.combo1.bind("<<ComboboxSelected>>",self.select_Combo)

    def select_Combo(self, event):
        self.var_Selected = self.combo1.current()
        print "The user selected value now is:"
        print  self.var_Selected
        # Any other function you want to use as function(self.var_Selected) or a function that gets self

app()