python - 为什么调用 entry.get() 给我 "invalid command name"?

标签 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()

当我调用代码时:

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"

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

最佳答案

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

关于python - 为什么调用 entry.get() 给我 "invalid command name"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33591874/

相关文章:

python - 使用 tkinter 网格

python - 从 Cygwin 启动 python IDLE 时 Tkinter 中的 tcl_error

python - tkinter 中 OtpionMenu 和 ComboBox 的区别

python - 是否可以 os.walk 2 个不同的文件目录并在遍历时将它们相互比较

python - 在Python中查找串口变化时有没有办法避免轮询?

python - 如何将列的值显示为单独的列

user-interface - ListTile中的图像

python - 函数装饰器

css - 如何删除 GTK 条目(文本框)边框?

asp.net - 在 asp.net 中显示用户消息的好方法的建议?