Home > Software design >  Tkinter Variable Not Updating(Defined outside of function)
Tkinter Variable Not Updating(Defined outside of function)

Time:05-19

I am working on an input box in tkinter. It is supposed to take a value in(in the entry), and once the "okay" button is pressed, that value will be assigned to a variable. Once the tkinter window is closed, the variable will be printed. Here is the code:

import tkinter as tk



root = tk.Tk()
root.title("Input")
root.geometry("400x200")

a = ""

entry1 = tk.Entry(root)
entry1.pack()


def entry1Input():
    a = entry1.get()
    print(a)

okay = tk.Button(root,text = "Okay", command = entry1Input())

okay.pack()



root.mainloop()

print("A: "   a)

The problem is that when I close out of the window, the value is the same as when I first defined it. I haven't coded python in a while, so this might be a simple error. Could you please let me know what the mistake is?

CodePudding user response:

You have two problems. First, you are not passing the function object here:

okay = tk.Button(root,text = "Okay", command = entry1Input())

Instead, you are CALLING the function. The function returns None, and that's what you send to command. You need:

okay = tk.Button(root,text = "Okay", command = entry1Input)

Then, the a in your function is local to that function, and goes away when the function ends. You need:

def entry1Input():
    global a

I sincerely hope you are not using a as your variable name here.

  • Related