Tkinter MessageBox出错

时间:2016-12-23 18:30:18

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

在用Python 3.5编写的GUI程序中,我使用了Tkinter模块。我定义了一个函数来调用MessageBox,如下所示:

def callAbout():
    messagebox.showinfo(title = "About", message = "My Window")

当我尝试执行时,收到以下错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
  [PATH]
    return self.func(*args)
  File "tk-error.py", line 4, in callAbout
    messagebox.showinfo(title = "About", message = "My Window")
NameError: name 'messagebox' is not defined

似乎程序找不到

messagebox

但我想知道为什么,因为我用

导入了整个模块
from tkinter import *

请询问您是否需要完整的代码。 在此先感谢您的帮助。

补充:以下是整个代码。

from tkinter import *

def callAbout():
    messagebox.showinfo(title = "About", message = "My Window")

win = Tk()

win.geometry('300x300')
win.title("My First Window")

bar_menu = Menu(win)

menu_about = Menu(bar_menu, tearoff = 0)
bar_menu.add_cascade(label = "About", menu = menu_about)
menu_about.add_command(label = "About", command = callAbout)

win.config(menu = bar_menu)

win.mainloop()

4 个答案:

答案 0 :(得分:0)

messagebox.showinfo更改为showinfo并添加from tkinter.messagebox import showinfo

from tkinter import *
from tkinter.messagebox import showinfo


def callAbout():
    showinfo(title="About", message="My Window")


win = Tk()

win.geometry('300x300')
win.title("My First Window")

bar_menu = Menu(win)

menu_about = Menu(bar_menu, tearoff=0)
bar_menu.add_cascade(label="About", menu=menu_about)
menu_about.add_command(label="About", command=callAbout)

win.config(menu=bar_menu)

win.mainloop()

输出:

enter image description here

答案 1 :(得分:0)

您可以使用别名导入和使用 messagebox 模块:

import tkinter.messagebox as tkmb

这是进行更改后的代码,

import tkinter as tk
import tkinter.messagebox as tkmb

def callAbout():
    tkmb.showinfo(title = "About", message = "My Window")

win = tk.Tk()

win.geometry('300x300')
win.title("My First Window")

bar_menu = tk.Menu(win)

menu_about = tk.Menu(bar_menu, tearoff = 0)
bar_menu.add_cascade(label = "About", menu = menu_about)
menu_about.add_command(label = "About", command = callAbout)

win.config(menu = bar_menu)

win.mainloop()

答案 2 :(得分:0)

我有同样的问题。 我这样更改了代码。简单地...


from tkinter import *

from tkinter import messagebox

答案 3 :(得分:0)

messagebox 以及其他一些模块(如 filedialog)在您导入 tkinter 时不会自动导入。根据需要使用 as 和/或 from 显式导入它。检查以下 3 个示例以获得更好的说明-

    >>> import tkinter
    >>> tkinter.messagebox.showinfo(message='hi')

Traceback (most recent call last): File "", line 1, in 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'