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)
:
JavaScript
x
21
21
1
secret = randrange(1,100)
2
print(secret)
3
def res(real, secret):
4
if secret==eval(real):
5
showinfo(message='that is right!')
6
real.delete(0, END)
7
8
def guess():
9
ge = Tk()
10
ge.title('guessing game')
11
12
Label(ge, text="what is your guess:").pack(side=TOP)
13
14
ent = Entry(ge)
15
ent.pack(side=TOP)
16
17
btn=Button(ge, text="Enter", command=lambda: res(ent.get(),secret))
18
btn.pack(side=LEFT)
19
20
ge.mainloop()
21
Advertisement
Answer
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:
JavaScript
1
22
22
1
import tkinter as tk
2
3
class App(tk.Frame):
4
def __init__(self, master):
5
tk.Frame.__init__(self, master, height=42, width=42)
6
self.entry = tk.Entry(self)
7
self.entry.focus()
8
self.entry.pack()
9
self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)
10
self.clear_button.pack()
11
12
def clear_text(self):
13
self.entry.delete(0, 'end')
14
15
def main():
16
root = tk.Tk()
17
App(root).pack(expand=True, fill='both')
18
root.mainloop()
19
20
if __name__ == "__main__":
21
main()
22