getting selected value of Combobox python

筅森魡賤 提交于 2021-02-05 11:14:27

问题


Hi I have the following code

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)

I want to send the selected value of from the Combobox to cityselection function but when I print it I only get

VirtualEvent event x=0 y=0

and it does not matter which value I choose I will always get the above output instate of for e.g: London or Toronto,


回答1:


this worked for me :

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()



回答2:


As it stands you cannot retrieve the value of geo, since it is not defined as an attribute of your class, but in the local scope of create. What you can do is declaring geo as a static attribute and then call it from within your method when you need it.

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)

Actually, event is not what you think it is.



来源:https://stackoverflow.com/questions/47371268/getting-selected-value-of-combobox-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!