Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

python - Entry box text clear when pressed Tkinter

I'm not sure whether this has been asked already or not, but I have multiple entry boxes in which contain a default piece of text. I am not trying to set a default piece of text, I'm trying to remove when the entry box is clicked. I want to be able to remove the default text as soon as the entry box is clicked so the user does not have to do so. I was wondering if someone could share a quick example on how this is done so I can implement.

    def removeValue(event):
        self.entry.delete(0, 'end')
        return None

    for i in range(1, numberOfStudents + 1):
        for p in range(0,2):
            self.entry = Entry(self.master)
            if p == 0:
                self.entry.insert(0, 'Enter name of student')
                self.entry.place(x = 10, y = (i * 30) + 26)
                self.entry.bind("<Button-1>", removeValue)
            if p == 1:
                self.entry.insert(0, 'Enter predicted')
                self.entry.place(x = (getWidth(master) - 140), y = (i * 30) + 26)
                self.entry.bind("<Button-1>", removeValue)

I have this so far, but only deletes the very last entry boxes text.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you've got your default text sorted out, you want to create an Event binding somewhere, with the general format of the comment above, not sure why it's not an answer, because it's right:

import tkinter as tk

root = tk.Tk()
e = tk.Entry(root)
e.insert(0, "some text")

def some_callback(event): # note that you must include the event as an arg, even if you don't use it.
    e.delete(0, "end")
    return None

e.bind("<Button-1>", some_callback)

e.pack()

Finally, http://effbot.org is your friend: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

EDIT: Additional info for OP from comment. If you have multiple entries and you need to clear each one individually, you can simply refer to the widget that called the bound method using

event.widget

Your callback could then work as follows:

def some_callback(event):
    event.widget.delete(0, "end")
    return None

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...