tkinter.messagebox.showinfo并不总是有效

v3n*_*774 4 python user-interface tkinter python-3.x

我刚开始使用Python的tkinterGUI工具.在我的代码中,我创建了一个带有一个按钮的简单GUI,我想向用户显示messagebox他们是否点击了按钮.

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

AttributeError:'module' object has no attribute 'messagebox'
Run Code Online (Sandbox Code Playgroud)

你有什么提示吗?我的代码是:

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()
Run Code Online (Sandbox Code Playgroud)

Tig*_*kT3 12

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'
Run Code Online (Sandbox Code Playgroud)

  • 有一个解决方案,它可以在 IDLE 中工作,它是用 tkinter 编写的。 (2认同)