Tkinter messagebox调用报错AttributeError,如何实现多功能弹窗?
Tkinter MessageBox调用报错:AttributeError: 'function' object has no attribute 'showwarning'
问题重现
你尝试在Tkinter中调用带多种样式的MessageBox,写出了如下代码:
from Tkinter import * from Tkinter import messagebox as msgbox *some code...* input1 = msgbox.askyesno.showwarning('title', 'blahblahblah') if input1 == 1: input2 = msgbox.askyesno.showwarning('title', 'blahblahblah') if input2 == 1: function()
运行时触发错误:
input1 = msgbox.askyesno.showwarning('title', 'blahblahblah') ^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'function' object has no attribute 'showwarning'
错误原因
msgbox.askyesno和msgbox.showwarning是Tkinter messagebox模块下两个独立的函数:
askyesno:弹出带Yes/No按钮的对话框,返回布尔值(True/False,对应你代码里的1/0)showwarning:弹出带警告图标的确认对话框,只有OK按钮
你错误地将这两个函数链式调用,而askyesno本身是一个函数对象,没有showwarning属性,因此触发AttributeError。
正确的Tkinter解决方案
如果你需要的是带警告图标的Yes/No对话框,可以直接给askyesno指定icon参数,无需链式调用:
from Tkinter import * from Tkinter import messagebox as msgbox def function(): # 这里是你要执行的功能代码 print("执行目标功能") # 弹出带警告图标的Yes/No对话框 input1 = msgbox.askyesno('title', 'blahblahblah', icon='warning') if input1: # 直接用布尔值判断即可,无需对比1 input2 = msgbox.askyesno('title', 'blahblahblah', icon='warning') if input2: function()
你找到的替代方案
如果更偏好使用系统原生对话框,也可以调用Windows API的MessageBox函数(需要借助ctypes库),补充完整后的示例代码如下:
import sys import ctypes from ctypes import wintypes # 加载user32.dll user32 = ctypes.WinDLL('user32', use_last_error=True) # 定义MessageBox的参数常量 MB_ICONWARNING = 0x00000030 MB_YESNO = 0x00000004 IDNO = 7 # 声明MessageBoxW的参数类型和返回值类型 user32.MessageBoxW.argtypes = (wintypes.HWND, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.UINT) user32.MessageBoxW.restype = wintypes.INT title = "title" description = "blahblahblah" if user32.MessageBoxW(None, description, title, MB_ICONWARNING | MB_YESNO) == IDNO: sys.exit(0)
内容的提问来源于stack exchange,提问作者ManiTheObbyist
相关产品推荐
相关产品推荐

