How to add a placeholder in Tkinter

2019-01-20 16:38发布

How would I add a placeholder to an entry in tkinter? I don't believe it has a placeholder function like HTML for example. I figured out that to make the text disappear when you click it, you will have to add an onclick event, but how do I create the onclick event and how do you make the text appear in the first place? Here is the code I'm working with.

I would like it to say " Enter your integer here"

Textbox

    vcmd = (self.register(self.onValidate), '%S')
    self.text = Entry(self, validate='key', vcmd=vcmd)
    self.text.pack()

def onValidate(self, S):
    if S in '0123456789.':
        return True
    return False

def clear_entry(self):
    self.text.delete(0, END)
    self.text.pack()

1条回答
闹够了就滚
2楼-- · 2019-01-20 17:05

U can't add placeholder like HTML as far as i know, but u can make similar behavior. When you make entry you can do something like>

from tkinter import *   

def clear_entry(event, entry):
    entry.delete(0, END)

root = Tk()

entry = Entry(root)

entry.pack()
placeholder_text = 'some text'
entry.insert(0, placeholder_text)

entry.bind("<Button-1>", lambda event: clear_entry(event, entry))

root.mainloop()

P.S: I've wrote this from my head , haven't tested it

查看更多
登录 后发表回答