【问题标题】:getting selected value of Combobox python获取 Combobox python 的选定值
【发布时间】:2020-05-17 11:54:29
【问题描述】:

您好,我有以下代码

def create(self):
    geo = StringVar()
    city = ttk.Combobox(gui, textvariable=geo,state="readonly")
    city.config(values=self.geo)
    city.pack()
    city.bind("<<ComboboxSelected>>", self.cityselection)


def cityselection(self,event):
    selected=event
    print(selected)

我想将 Combobox 中的选定值发送到 cityselection 函数,但是当我打印它时,我只得到

VirtualEvent 事件 x=0 y=0

不管我选择哪个值,我总是会得到上述输出状态,例如:伦敦或多伦多,

【问题讨论】:

  • 在这两种方法中都使用self.geo 来访问选定的元素。

标签: python tkinter combobox


【解决方案1】:

就目前而言,您无法检索geo 的值,因为它没有定义为您的类的属性,而是在create 的本地范围内。您可以做的是将geo 声明为静态属性,然后在需要时从您的方法中调用它。

class(object):

    geo = StringVar()
    geos = ('NY','LA','RY','...')

    def __init__(self,#....
        #...

    def create(self):
        city = ttk.Combobox(gui, textvariable=self.geo,state="readonly")
        city.config(values=self.geos) 
        city.pack()
        city.bind("<<ComboboxSelected>>", self.cityselection)


    def cityselection(self,event):
        selected=self.geo.get()
        print(selected)

其实event并不是你想的那样。

【讨论】:

  • 我正在尝试使用的列表是 所以我认为当组合框显示它时,它会将整个数组显示为一个
  • @Amin 我不确定您为什么在讨论中涉及列表。顺便说一句,如果 foo 是你的 numpy.ndarray 的名称,你可以做些什么来把它变成一个所谓的 python 内置 list,是 foo.tolist()。
【解决方案2】:

这对我有用:

def create(self):
        print(self.geo)
        strgeo="\n".join(str(x) for x in self.geo)

        print(strgeo)
        city = ttk.Combobox(gui, textvariable=self.stringGeo, state="readonly",width=30)
        city.config(values=strgeo)
        city.pack()
        city.bind("<<ComboboxSelected>>",self.selectedCity)

    def selectedCity(self,event):
        selected=self.stringGeo.get()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多