Home > front end >  Python tkinter kept saying my variable to hold the .get() value is not defined
Python tkinter kept saying my variable to hold the .get() value is not defined

Time:11-11

I am learning how to use the .get() for tkinter, and trying to write this basic GUI that can store, process, and display data depending on a user input.

Now (I am fairly new to this, so I am probably wrong) to my knowledge, I need to use the .get() and store it into a variable for future uses.

Now here are my codes, but when I run the code, it kept saying I did not define my variable in the function I defined.

I wrote in Pycharm, the variable I wrote in the first line of the function just keep turning grey.

Why is this happening, am I missing something important?

Sidenote:

I have done some research and saw some result regarding using the following method:

  1. StringVar()
  2. fstring, f"{}"

but I still can't figure out how that works and how it is affecting my code that Python is not accepting my variable.


Import tkinter as tk

def event():
    expEntry = entry.get()

window = tk.Tk()

entry = tk.Entry(window)
button = tk.Button(window,commnad=event())
expEntry = tk.Label(window,text = expEntry)

entry.pack()
button.pack()
expEntry.pack()

window.mainloop()

CodePudding user response:

You should use a StringVar to store the value of the entry when event() is called by button

import tkinter as tk


def event():  # use this function to update the StringVar
    entry_content = entry.get()
    entry_var.set(entry_content)


window = tk.Tk()
# declare a StringVar to store the value of your Entry and update your Label
entry_var = tk.StringVar(window, 'Default Text')
# use 'textvariable' here to update the label when the bound variable changes
expEntry = tk.Label(window, textvariable=entry_var)
entry = tk.Entry(window)
# there was a typo in 'command' here, FIY
button = tk.Button(window, text='Press me', command=event)  

entry.pack()
button.pack()
expEntry.pack()
window.mainloop()

Note: you don't need the () for the command binding, as you're not calling the event function there! You're just telling the button the name of the function it should call.

CodePudding user response:

Easier way to do this. Just added tk.StringVar().

import tkinter as tk

window = tk.Tk()
window.geometry("700x300")
window.title("StringVar Object in Entry Widget")
var =tk.StringVar(window)

def event():   
   Label2.config(text=var.get())

myEntry = tk.Entry(window, textvariable=var)
myEntry.pack()

myButton = tk.Button(window, text="Submit", command=event)
myButton.pack()

Label2 = tk.Label(window, font="Calibri,10")
Label2.pack()

window.mainloop()

Output before:

enter image description here

Output after:

enter image description here

  • Related