2016-06-11 68 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() 

我所做的只是附加一個trace()方法STRINGVAR並刪除了command參數,你是路過。

+0

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