Montè Clements
Montè Clements

Reputation: 53

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.

Upvotes: 4

Views: 15179

Answers (2)

Blackbeard
Blackbeard

Reputation: 355

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

Upvotes: 11

Bryan Oakley
Bryan Oakley

Reputation: 385940

The method called by the event binding is given an event object. This object has a reference to the widget that triggered the event. You can use that to clear the widget:

def removeValue(event):
    event.widget.delete(0, 'end')

Upvotes: 1

Related Questions