How to fix KeyError for key from control variable get() method How to fix KeyError for key from control variable get() method tkinter tkinter

How to fix KeyError for key from control variable get() method


import tkinter as tkfrom tkinter import ttkwindow = tk.Tk()window.geometry('300x300')window.title('test')def showResult():    x = var.get()    message = list(my_Dict[x].values())    result.set(str(message))my_Dict= {'A': {'aa': 1}, 'B': {'bb': 2}, 'C': {'cc': 3}}label = ttk.Label(window, text='Enter here').grid(row=0, column=0)var = tk.StringVar()entry1 = ttk.Entry(window, textvariable=var).grid(row=0, column=1)label = ttk.Label(window, text='"Result here').grid(row=2, column=0)result = tk.StringVar()entry2 = ttk.Entry(window, textvariable=result).grid(row=2, column=1)btn = ttk.Button(window, text='SHOW', command=lambda: showResult())btn.grid(row=1, column=0)window.mainloop()

The problem was in the showResult() procedure and the declaration of the 'btn' object.When the btn created the connected slot will called but at this time the var object is an empty string. That will occur a prompt KeyError exception in showResult() at the decleration of the message object.

Use instead a lambda expression or refactor the showResult() like this:

def showResult():    x = var.get()    if x in my_Dict.keys():        message = list(my_Dict[x].values())        result.set(str(message))btn = ttk.Button(window, text='SHOW', command=showResult)