Home > front end >  StringVar doesn't update in an entry when using tkinter
StringVar doesn't update in an entry when using tkinter

Time:11-09

EDIT: Some of the code in the image is wrong, the code in the block is my updated code that also has the same issue.

As you can see in the image below, I'm having an issue where the StringVar does not update when I type in the Entry. I've searched and found code and error

CodePudding user response:

At the start of your code you defined two stringvars, 'uname' and 'pword'. Those are the variables that are checked in the button.command function. However when you create your username and password fields, you create two new stringvars, 'username' and 'password'. Those are the variables that are updated by the textboxes.

To fix it, simply make sure the text fields are bound to the same variables as the button. Here's your fixed code:

def start():
  login = Tk()
  uname = StringVar()
  pword = StringVar()

  def check(username, password):
    print("username entered :", username.get())
    print("password entered :", password.get())
    return

  Label(login, text="User Name").grid(row=0, column=0)
  usernameEntry = Entry(login, textvariable=uname).grid(row=0, column=1)  

  #password label and password entry box
  Label(login,text="Password").grid(row=1, column=0)  
  passwordEntry = Entry(login, textvariable=pword, show='*').grid(row=1, column=1)

  Button(login, text="Submit", command=lambda: check(uname, pword)).grid(row=2, column=1)

  login.mainloop()

CodePudding user response:

I messed around with the code for a while and eventually I got it to work!

I had to state that the StringVar variables belonged to the login window.

Working code:

def check():
  print("test")
  print("username entered :", uname.get())
  print("password entered :", pword.get())
  return

def start():
  global uname, pword
  login = Tk()
  uname = StringVar(login)
  pword = StringVar(login)

  Label(login, text="User Name").grid(row=0, column=0)
  usernameEntry = Entry(login, textvariable=uname).grid(row=0, column=1)  

  #password label and password entry box
  Label(login,text="Password").grid(row=1, column=0)  
  passwordEntry = Entry(login, textvariable=pword, show='*').grid(row=1, column=1)

  Button(login, text="Submit", command=check).grid(row=2, column=1)

  login.mainloop()
  • Related