tkinter.messagebox.showinfo 并不总是有效

tkinter.messagebox.showinfo doesn't always work

我刚刚开始使用 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()

区分大小写 - tkinter 在任何地方都应该是 Tkinter。我这样做了,并且能够 运行 你的例子。

messagebox 以及 filedialog 等其他一些模块不会在您 import tkinter 时自动导入。根据需要使用 as and/or 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'