我试图使一个占位符重新出现在输入小部件当用户没有放任何东西,但点击离开,在Tkinter/python。请帮助。
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)
您必须绑定到用户单击远离条目并检查它是否为空。如果为空,则插入占位符文本。
下面是工作代码:
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()