Why does calling entry.get() give me “invalid command name”?

a 夏天 提交于 2019-12-19 10:07:08

问题


This is my code:

def ask(what,why):
    root=Tk()
    root.title(why)
    label=Label(root,text=what)
    label.pack()
    entry=Entry(root)
    entry.pack()
    button=Button(root,text='OK',command=root.destroy)
    button.pack()
    root.mainloop()
    return entry.get()

And when I call the code:

print(ask('Name:','Hello!'))

I get:

Traceback (most recent call last):
  File "C:\gui.py", line 16, in <module>
    ask('Name:','Hello!')
  File "C:\gui.py", line 15, in ask
    return entry.get()
  File "C:\Python34\lib\tkinter\__init__.py", line 2520, in get
    return self.tk.call(self._w, 'get')
_tkinter.TclError: invalid command name ".48148176"

I am using Python 3.4.3 on 32-bit Windows 7.


回答1:


When you press the button, the application is destroyed, the mainloop ends, and you try to return the contents of an Entry widget... in an application that was destroyed. You need to save the contents of entry before destroying the application. Instead of hacking your way through this, it would be much better to set up a Tkinter application in the proper way, such as with an object-oriented approach.

class App:
    # 'what' and 'why' should probably be fetched in a different way, suitable to the app
    def __init__(self, parent, what, why):
        self.parent = parent
        self.parent.title(why)
        self.label = Label(self.parent, text=what)
        self.label.pack()
        self.entry = Entry(self.parent)
        self.entry.pack()
        self.button = Button(parent, text='OK', command=self.use_entry)
        self.button.pack()
    def use_entry(self):
        contents = self.entry.get()
        # do stuff with contents
        self.parent.destroy() # if you must

root = Tk()
app = App(root, what, why)
root.mainloop()


来源:https://stackoverflow.com/questions/33591874/why-does-calling-entry-get-give-me-invalid-command-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!