在Tkinter中没有输入的情况下取消选择输入字段时,使占位符重新出现

2024-04-29 02:06:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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)

Tags: 用户event内容部件tkinterdef条目place
1条回答
网友
1楼 · 发布于 2024-04-29 02:06:53

您必须绑定到用户,并检查其是否为空。如果为空,则插入占位符文本

这是工作代码:

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()

相关问题 更多 >