Python Tkinter组合框和字典

时间:2019-01-21 05:34:31

标签: python dictionary tkinter combobox

我是Python的新手,并且遇到了以下问题。我创建了一个字典,材质为Key,折射率为Value。

用户可以从组合框中选择材料。同时,我想显示所选材料的折射率。但是我无法使它起作用! 下面是我的代码。感谢您的帮助。

from tkinter import *
from tkinter import ttk

def main():

    materialDict = {'XO': 1.415, 'XO2': 1.424, 'Opt-EX': 1.431, 'TYRO-97': 1.44, 'AC-100': 1.415, 'Paragon': 1.442}

    root = Tk()
    root.geometry("1600x800+0+0")
    root.title("TEST Form")
    root.configure(bg='Dodgerblue4')

    label_material = Label(root, text='Choose Material', bd=3, width=20, height=3).grid(row=0, column=1)
    var_material = StringVar()
    combo_material = ttk.Combobox(root, values=list(materialDict.keys()), justify=CENTER, textvariable=var_material)
    combo_material.grid(row=0, column=2)
    combo_material.current(0)

    label_selected = Label(root, text="Here I want to print the value of the combobox selected item ")
    label_selected.grid(row=1, column=3)

    root.mainloop()

    return

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:1)

可以使用lambda完成。您需要将<<ComboboxSelected>>事件绑定到回调函数。除了自己编写标签功能之外,我还在那里完成了标签配置。

import tkinter as tk
from tkinter import ttk

def main():

    materialDict = {'XO': 1.415, 'XO2': 1.424, 'Opt-EX': 1.431, 'TYRO-97': 1.44, 'AC-100': 1.415, 'Paragon': 1.442}

    root = tk.Tk()
    root.title("TEST Form")
    root.configure(bg='Dodgerblue4')

    tk.Label(root, text='Choose Material', bd=3).grid(row=0, column=0)
    var_material = tk.StringVar()
    combo_material = ttk.Combobox(root, values=list(materialDict.keys()), justify="center", textvariable=var_material)
    combo_material.bind('<<ComboboxSelected>>', lambda event: label_selected.config(text=materialDict[var_material.get()]))
    combo_material.grid(row=0, column=1)
    combo_material.current(0)

    label_selected = tk.Label(root, text="Not Selected")
    label_selected.grid(row=1, column=1)

    root.mainloop()

if __name__ == '__main__':
    main()

Demo