2013-07-20 30 views
8

Điều này sẽ rất đơn giản nhưng tôi thực sự đang gặp khó khăn để làm cho nó đúng. Tất cả những gì tôi cần là một ComboBox ttk đơn giản, cập nhật một biến số về thay đổi lựa chọn.Bản demo ttk ComboBox đơn giản

Trong ví dụ bên dưới, tôi cần giá trị của biến số value_of_combo để được cập nhật tự động mỗi khi có lựa chọn mới.

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

Trả lời

13

Chỉ cần ràng buộc sự kiện ảo <<ComboboxSelected>> để widget Combobox:

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

Trong trường hợp tổng quát hơn, nếu bạn cần để có được giá trị của một biến khi nó được cập nhật, nó sẽ được khuyến khích để sử dụng cơ sở truy tìm được tích hợp vào chúng.

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 
Các vấn đề liên quan