Search code examples
pythonvariablestkintertextkeyerror

Tkinter: KeyError when assigning function to a button


So, I have rather complicated program, and I ran into an issue with it that I can't seem to solve. Here's the problematic part of my program:

import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()

def hi():
    text = vars()[variable].get()

button = tk.Button(text = "Click", command = hi)
button.pack()

I need to get the content of the entry called "enter" with the press of a button. Because of how my program works, this name, "enter" must be stored in a variable, that I called "variable" here. What happens, is that when I press the button, I get a KeyError.

What's even weirder is that when I do the following, the program actualy works:

import tkinter as tk
window = tk.Tk()
variable = "enter"
vars()[variable] = tk.Entry()
vars()[variable].insert(0, "hello")
vars()[variable].pack()


text = vars()[variable].get()

button = tk.Button(text = "Click")
button.pack()

Here getting the content of "enter" isn't done with a button, but it's done automatically as the program runs. This is not what I want, but for some reason it works.

What can I do to make the 1st code work properly?


Solution

  • When you execute vars locally within hi function, a new dict object is created, that is different than the dict object created globally.
    You can save the reference to the variable and use the variable within your hi function.

    import tkinter as tk
    
    window = tk.Tk()
    variable = "enter"
    vars()[variable] = tk.Entry()
    vars()[variable].insert(0, "hello")
    vars()[variable].pack()
    
    d = vars()
    
    def hi():
        text = d[variable].get()
    
    button = tk.Button(text="Click", command=hi)
    button.pack()
    
    window.mainloop()