0

I'm trying to make a placeholder reappear in the entry widget when the user hasn't put anything in but clicked away, in Tkinter/python. Please Help.

def windTurbineHeightClear(event):

    windTurbineHeight.delete(1, 'end')

windTurbineHeight = tk.Entry(window, width=10)
windTurbineHeightPlaceholder = ' Height'
windTurbineHeight.insert(0, windTurbineHeightPlaceholder)
windTurbineHeight.bind("<Button-1>", windTurbineHeightClear)
windTurbineHeight.place(x=320, y=108, width=320, height=34)city.place(x=320, y=108, width=320, height=34)
Jakub Szlaur
  • 1,852
  • 10
  • 39

1 Answers1

1

You have to bind to the user clicking away from the entry and check if it is empty. If it is empty then insert the placeholder text.

This is the code working:

import tkinter as tk


def when_unfocused(event):
    text_in_entry = windTurbineHeight.get() # Get the text
    if text_in_entry == "": # Check if there is no text
        windTurbineHeight.insert(0, windTurbineHeightPlaceholder) # insert the placeholder if there is no text

def windTurbineHeightClear(event):
    windTurbineHeight.delete(0, 'end') # btw this should be 0 instead of 1


window = tk.Tk()
windTurbineHeight = tk.Entry(window, width=10)


windTurbineHeightPlaceholder = 'Height'
windTurbineHeight.insert(0, windTurbineHeightPlaceholder)
windTurbineHeight.bind("<FocusOut>", when_unfocused) # When the user clicks away
windTurbineHeight.bind("<FocusIn>", windTurbineHeightClear) # When the user clicks on the entry

windTurbineHeight.pack()

window.mainloop()
TheLizzard
  • 7,248
  • 2
  • 11
  • 31