簡體   English   中英

獲取 Combobox python 的選定值

[英]getting selected value of Combobox python

嗨,我有以下代碼

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

我選擇哪個值並不重要,我將始終獲得上述輸出狀態,例如:倫敦或多倫多,

這對我有用:

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

就目前而言,您無法檢索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並不是你想的那樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM