根据Key in Dropdown菜单更新标签Tkinter Python

时间:2016-06-11 04:36:56

标签: python tkinter

您好我正在尝试根据从下拉菜单中选择的键更新标签(使用字典)。我不确定如何更新标签。谢谢。我已尝试如下,但由于缺乏知识,我显然做错了。谢谢你

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 个答案:

答案 0 :(得分: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参数。