【问题标题】:tkinter.messagebox.showinfo doesn't always worktkinter.messagebox.showinfo 并不总是有效
【发布时间】:2015-06-28 18:36:32
【问题描述】:

我刚刚开始使用 Python 的 tkinter GUI 工具。在我的代码中,我创建了一个带有一个按钮的简单 GUI,如果用户单击该按钮,我想向用户显示 messagebox

目前,我使用tkinter.messagebox.showinfo 方法。我使用 IDLE 在 Windows 7 计算机上编码。如果我从 IDLE 运行代码一切正常,但如果我尝试在 Python 3 解释器中独立运行它,它就不再工作了。相反,它会将此错误记录到控制台:

AttributeError:'module' object has no attribute 'messagebox'

你有什么建议给我吗?我的代码是:

import tkinter

class simpleapp_tk(tkinter.Tk):
    def __init__(self,parent):
        tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.temp = False
        self.initialize()

    def initialize(self):
        self.geometry()
        self.geometry("500x250")
        self.bt = tkinter.Button(self,text="Bla",command=self.click)
        self.bt.place(x=5,y=5)
    def click(self):
        tkinter.messagebox.showinfo("blab","bla")

if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('my application')
    app.mainloop()

【问题讨论】:

  • 能否提供完整的错误回溯,格式为代码?
  • 尝试导入模块messagebox,然后将tkinter.messagebox.showinfo("blab","bla")替换为messagebox.showinfo("blab","bla"),看看是否有变化。

标签: python user-interface python-3.x tkinter


【解决方案1】:

messagebox 以及像filedialog 这样的其他一些模块不会在您import tkinter 时自动导入。根据需要使用as 和/或from 显式导入它。

>>> import tkinter
>>> tkinter.messagebox.showinfo(message='hi')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'messagebox'
>>> import tkinter.messagebox
>>> tkinter.messagebox.showinfo(message='hi')
'ok'
>>> from tkinter import messagebox
>>> messagebox.showinfo(message='hi')
'ok'

【讨论】:

  • 就是这样(从 tkinter 导入消息框)感谢您的解决方案,我不知道它为什么通过使用 IDLE 起作用,但使用此解决方案它可以工作。
  • 有一个解决方案,它可以在 IDLE 中工作,它是用 tkinter 编写的。
【解决方案2】:

这是区分大小写的 - 无论在哪里使用 tkinter 都应该是 Tkinter。我这样做了,并且能够运行您的示例。

【讨论】:

猜你喜欢
  • 2012-12-26
  • 1970-01-01
  • 1970-01-01
  • 2012-04-23
  • 2015-12-04
  • 2017-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多