Search code examples
pythontkintertracetkinter-entry

Problem with Tkinter using StringVar(), trace() and Entry()


I am defining a StringVar() and giving it a value, then using it as the textvariable of an Entry widget. I have also added a trace to the StringVar so that I can use it as a placeholder checker and make the placeholder a different colour to the typed text.

However, when I run the code the entry widget contains no text, but if I print the value of the StringVar() it gives the correct value. Also, the trace command is never called and when I print the value of the textvariable of the Entry widget, it comes out as PY_VAR#.

Does anyone know why this is not working and how to solve it?

circleVarEmailAddress = StringVar()
circleVarEmailAddress.set("email address")
circletextEmailAddress = Entry(forgottenWindow, textvariable = circleVarEmailAddress,
                               font = 10, relief = "raised", highlightbackground = "black",
                               borderwidth = 2, fg = "#808080")
circletextEmailAddress.place(x = 75, y = 100, width = 250, height = 50)

def placeholderEmailAddress(a, b, c):
  print("Hey")
  for i in range(1, 13):
    if("email address"[:i] in circleVarEmailAddress.get() == True and
       "email address"[i:] in circleVarEmailAddress.get() == True):
      index1 = circleVarEmailAddress.get().index("email address"[:i])
      index2 = circleVarEmailAddress.get().index("email address"[i:])
      circleVarEmailAddress.set(circleVarEmailAddress.get()[:index1] +
                                circleVarEmailAddress.get()[index1 + i:index2] +
                                circleVarEmailAddress.get()[index2 + 13 - i:])
  if(circleVarEmailAddress.get() != "email address" and
     "email address" in circleVarEmailAddress.get() == True):
    circleVarEmailAddress.set(circleVarEmailAddress.get().replace("email address", ""))
  if circleVarEmailAddress.get() == "":
    circleVarEmailAddress.set("email address")
  if circleVarEmailAddress.get() == "email address":
    circletextEmailAddress.config(fg = "#808080")
  else:
    circletextEmailAddress.config(fg = "#000000")

circleVarEmailAddress.trace_add("write", placeholderEmailAddress)

Solution

  • Your code runs fine for me if I add some boilerplate.

    I assume from the variable name "forgottenWindow" that this is a new window in your program. The problem you are seeing can happen if you use Tk() to make additional windows. Always use Toplevel to make new windows beyond your first one.

    forgottenWindow = Toplevel()