I am trying to remove an Entry field after a user gives his/her name, however, I get an error using this code:
from Tkinter import *
from random import randrange
class Application(Frame):
def __init__(self):
Frame.__init__(self)
self.grid()
self.nameEntry = Entry(self)
self.nameEntry.grid(row=0, column=0, columnspan=4)
self.setupBtn = Button(self, text = "Generate", command=self.setup)
self.setupBtn.grid(row=4, column=0, columnspan=4)
self.preText = Text(self, width=50, height=3, wrap=WORD)
self.preText.grid(row=6, column=0, columnspan=4)
self.preText.delete(0.0, END)
self.preText.insert(0.0, "If you enter your name, i'll give you a random number each time!")
self.statusLbl = Label(self, text="What's your name?", bg="white")
self.statusLbl.grid(row=7, column=0, columnspan=4, sticky=W)
def setup(self):
name = self.nameEntry.get()
if name != "":
self.nameEntry.destroy()
self.setupBtn = Button(self, text = "Roll Again", command=self.setup)
self.setupBtn.grid(row=4, column=0, columnspan=4)
randomNumber = randrange(10, 100)
if name == "":
message = "Your name please!"
self.preText.delete(0.0, END)
self.preText.insert(0.0, message)
else:
self.preText.delete(0.0, END)
self.preText.insert(0.0, str(randomNumber))
Application().mainloop()
Here is the error:
Exception in Tkinter callback Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__ return self.func(*args) File "C:/Users/User/Desktop/app.py", line 25, in setup name = self.nameEntry.get() File "C:\Python27\lib\lib-tk\Tkinter.py", line 2391, in get return self.tk.call(self._w, 'get') TclError: invalid command name ".45073096L.45073736L"
I would like to remove the name Entry field after a user enters the name and clicks the roll button. But instead of rolling, I get that error.
Is anyone able to help me? From what I know, it is because name = self.nameEntry.get() is used to store into name and therefore, when I delete it, it causes a problem. Do you have a workaround for it? I am not very good and am therefore unsure of how to proceed.
Two choices here:
(Quick & dirty) You could change the first if in setup() to be:
grid_forget() causes Tk to remove the widget but not actually destroy it. Also, you don’t need to recreate your button, you can just tell it to change its text. Another way to do it would be to set self.name=None in
__init__and change setup() to:Unfortunately I’ve not found one good central source of info for Tkinter/ttk, but here are the ones I have found:
Use ttk widgets whenever you can, they make your apps look much more like native host apps. As for Tix, it’s there mostly for backwards compatibility.