为什么调用entry.get()会给我“无效的命令名”?

Onk*_*Guy 2 python user-interface tkinter tkinter-entry

这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

当我调用代码时:

print(ask('Name:','Hello!'))
Run Code Online (Sandbox Code Playgroud)

我得到:

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"
Run Code Online (Sandbox Code Playgroud)

我在32位Windows 7上使用Python 3.4.3。

Tig*_*kT3 5

当您按下按钮时,应用程序被破坏,mainloop结束,然后您尝试返回Entry被破坏的应用程序中小部件的内容。您需要entry在销毁应用程序之前保存的内容。与其破解自己的方式,不如以一种合适的方式(例如,采用面向对象的方法)来设置Tkinter应用程序。

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()
Run Code Online (Sandbox Code Playgroud)