I'm trying to clear the Entry
widget after the user presses a button using Tkinter.
I tried using ent.delete(0, END)
, but I got an error saying that strings don't have the attribute delete.
Here is my code, where I'm getting error on real.delete(0, END)
:
secret = randrange(1,100) print(secret) def res(real, secret): if secret==eval(real): showinfo(message='that is right!') real.delete(0, END) def guess(): ge = Tk() ge.title('guessing game') Label(ge, text="what is your guess:").pack(side=TOP) ent = Entry(ge) ent.pack(side=TOP) btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret)) btn.pack(side=LEFT) ge.mainloop()
The content of the text widget can be cleared by defining the delete(0, END) command. Similarly, we can clear the content by clicking the Entry widget itself. This can be achieved by binding the function with a click event.
While creating a canvas in tkinter, it will effectively eat some memory which needs to be cleared or deleted. In order to clear a canvas, we can use the delete() method. By specifying “all”, we can delete and clear all the canvas that are present in a tkinter frame.
In order to delete the input content, we can use the delete("start", "end") method.
If you want to permanently delete it, call destroy on the widget (then you won't be able to re-add it). If you use the grid method, you can use grid_forget or grid_remove to hide the widget.
After poking around a bit through the Introduction to Tkinter, I came up with the code below, which doesn't do anything except display a text field and clear it when the "Clear text"
button is pushed:
import tkinter as tk class App(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master, height=42, width=42) self.entry = tk.Entry(self) self.entry.focus() self.entry.pack() self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text) self.clear_button.pack() def clear_text(self): self.entry.delete(0, 'end') def main(): root = tk.Tk() App(root).pack(expand=True, fill='both') root.mainloop() if __name__ == "__main__": main()
I'm unclear about your question. From http://effbot.org/tkinterbook/entry.htm#patterns, it seems you just need to do an assignment after you called the delete. To add entry text to the widget, use the insert method. To replace the current text, you can call delete before you insert the new text.
e = Entry(master) e.pack() e.delete(0, END) e.insert(0, "")
Could you post a bit more code?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With