2016-06-11 3 views
1

안녕하세요, 사전을 사용하여 드롭 다운 메뉴에서 선택한 키를 기반으로 레이블을 업데이트하려고합니다. 나는 라벨을 어떻게 업데이트 할 수 있는지 확신 할 수 없다. 고맙습니다. 아래에 나와있는 시도를했지만 지식이 부족하기 때문에 분명히 잘못하고 있습니다. 감사합니다는드롭 다운 메뉴의 키 기반 레이블 업데이트 Tkinter Python

from tkinter import * 
from tkinter.ttk import * 
import csv 


class DictionaryGui: 
'''Display a GUI allowing key->value lookup''' 
def __init__(self, parent, row, column, dictionary): 
    self.dictionary = dictionary 
    self.selection = StringVar() 
    self.value = StringVar() 

    username_label = Label(parent, text="Key:") 
    username_label.grid(row=row, column=column) 
    keys = list(sorted(dictionary.keys())) 
    self.selection.set(keys[0]) 
    select = Combobox(parent, textvariable=self.selection, 
         values=keys, 
         width=8, command=self.update()) 
    select.grid(row=row, column=column+1) 




    name = Label(parent, textvariable=self.value) 
    name.grid(row=row, column=column+3) 

def update(self): 
    self.value.set(self.dictionary[self.selection.get()]) 





def main(): 
    window = Tk() 
    test_dict = {'first_name': 'Fred', 'last_name': 'Bloggs', 'age' : 20} 
    gui = DictionaryGui(window, 0, 0, test_dict) 
    window.mainloop() 

main() 

답변

1

이 시도 : 내가 무슨 짓을

from Tkinter import * 
from ttk import * 
import csv 


class DictionaryGui: 
'''Display a GUI allowing key->value lookup''' 
def __init__(self, parent, row, column, dictionary): 
    self.dictionary = dictionary 
    self.selection = StringVar() 
    self.value = StringVar() 

    username_label = Label(parent, text="Key:") 
    username_label.grid(row=row, column=column) 
    keys = list(sorted(dictionary.keys())) 
    self.selection.trace('w', self.update) ## Added this line 
    self.selection.set(keys[0]) 
    select = Combobox(parent, textvariable=self.selection, 
         values=keys, 
         width=8) 
    select.grid(row=row, column=column+1) 

    name = Label(parent, textvariable=self.value) 
    name.grid(row=row, column=column+3) 

def update(self, *a): 
    self.value.set(self.dictionary[self.selection.get()]) 

def main(): 
    window = Tk() 
    test_dict = {'first_name': 'Fred', 'last_name': 'Bloggs', 'age' : 20} 
    gui = DictionaryGui(window, 0, 0, test_dict) 
    window.mainloop() 

main() 

간단했다 StringVar에 trace() 방법을 장착하고 통과 된 command 매개 변수를 제거했습니다.

+0

출처 : [link] (http://effbot.org/tkinterbook/variable.htm) – Zeerorg

관련 문제