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

时间:2015-11-08 07:55:17

标签: python user-interface tkinter tkinter-entry

这是我的代码:

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

当我打电话给代码时:

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"

我明白了:

insert_amount

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

1 个答案:

答案 0 :(得分:4)

当您按下按钮时,应用程序将被销毁,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()