Reputation: 57
I am new in Python and have stuck in the following problem. I have created a dictionary with material as Key and refractive index as Value.
From a combo-box a user chooses the material. At the same time, I would like to show the refractive index of the selected material. But I can't get it worked! Here-under is my code. Thanks for your help.
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()
Upvotes: 1
Views: 6160
Reputation: 4407
It can be done using a lambda
. You need to bind the <<ComboboxSelected>>
event to a callback function. Instead of writing a separate function, I have done the label configuration there itself.
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()
Upvotes: 7