为什么调用 entry.get() 会给我“无效的命令名称"? [英] Why does calling entry.get() give me "invalid command name"?

查看:26
本文介绍了为什么调用 entry.get() 会给我“无效的命令名称"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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.

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

推荐答案

当你按下按钮时,应用程序被销毁,mainloop 结束,你尝试返回一个 Entry 小部件...在被破坏的应用程序中.在销毁应用程序之前,您需要保存entry 的内容.与其通过这种方式破解,不如以适当的方式设置 Tkinter 应用程序,例如使用面向对象的方法.

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

这篇关于为什么调用 entry.get() 会给我“无效的命令名称"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆