gpt4 book ai didi

python - 根据下拉菜单中的键更新标签 Tkinter Python

转载 作者:太空宇宙 更新时间:2023-11-03 16:29:16 25 4
gpt4 key购买 nike

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

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

最佳答案

试试这个:

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 参数。

关于python - 根据下拉菜单中的键更新标签 Tkinter Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37759978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com