微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

用户在 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,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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。