2013-07-20 6 views
8

これは非常にシンプルなはずですが、私はそれを正しくするには本当に苦労しています。 私が必要とするのは、選択の変更時に変数を更新する単純なttk ComboBoxです。シンプルなttk ComboBoxデモ

以下の例では、新しい選択が行われるたびに自動的に変数value_of_comboの値を更新する必要があります。

from Tkinter import * 
import ttk 

class App: 

    value_of_combo = 'X' 


    def __init__(self, parent): 
     self.parent = parent 
     self.combo() 

    def combo(self): 
     self.box_value = StringVar() 
     self.box = ttk.Combobox(self.parent, textvariable=self.box_value) 
     self.box['values'] = ('X', 'Y', 'Z') 
     self.box.current(0) 
     self.box.grid(column=0, row=0) 

if __name__ == '__main__': 
    root = Tk() 
    app = App(root) 
    root.mainloop() 

答えて

13

だけでコンボボックスウィジェットに仮想イベント<<ComboboxSelected>>をバインド:より一般的なケースでは

class App: 
    def __init__(self, parent): 
     self.parent = parent 
     self.value_of_combo = 'X' 
     self.combo() 

    def newselection(self, event): 
     self.value_of_combo = self.box.get() 
     print(self.value_of_combo) 

    def combo(self): 
     self.box_value = StringVar() 
     self.box = ttk.Combobox(self.parent, textvariable=self.box_value) 
     self.box.bind("<<ComboboxSelected>>", self.newselection) 
     # ... 
3

あなたはそれが更新されたときに変数の値を取得する必要がある場合は、それが賢明だろうそれらに組み込まれているトレース機能を使用します。

var = StringVar() # create a var object 

# define the callback 
def tracer(name, idontknow, mode): 
    # I cannot find the arguments sent to the callback documented 
    # anywhere, or how to really use them. I simply ignore 
    # the arguments, and use the invocation of the callback 
    # as the only api to tracing 
    print var.get() 

var.trace('w', tracer) 
# 'w' in this case, is the 'mode', one of 'r' 
# for reading and 'w' for writing 

var.set('Foo') # manually update the var... 

# 'Foo' is printed 
関連する問題