Update label based on Key in Dropdown menu Tkinter Python -
hi trying update label based on key selected drop down menu (using dictionary). unsure how can update label. thankyou. have made attempt below doing wrong due lack of knowledge. thankyou
from tkinter import * tkinter.ttk import * import csv class dictionarygui: '''display 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()
try this:
from tkinter import * ttk import * import csv class dictionarygui: '''display 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 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()
what did attach trace()
method stringvar , removed command
parameter passing.
Comments
Post a Comment