作用的简单介绍
QMessageBox提供了一个对话框,用于提醒或者通知用户一些事情,用户并且可以与其进行交互。
按键类型
1.QMessageBox.Ok
2.QMessageBox.Close
3.QMessageBox.Cancel
4.QMessageBox.Open
5.QMessageBox.Save
类型
在PyQt5中QMessageBox提供了一些类型的对话框:
1.询问框:QMessageBox.question()
2.信息框:QMessageBox.information()
3.警告框:QMessageBox.warning(parent,title,text,buttons,defaultButton)
4.错误框:QMessageBox.critical(parent,title,text,buttons,defaultButton)
5.关于框:QMessageBox.about(parent,title,text)
询问框
参数:QMessageBox.question(parent,title,content,button)
parent:表示对话框所属的程序窗口,填写父类(通常为self);若没有则填None
title:标题
content:内容
button:对话框的按键
返回值:QMessageBox.Yes或者QMessageBox.No
import sys
from PyQt5.QtWidgets import QApplication,QPushButton,QWidget,QMessageBox,QVBoxLayout
class Simple_Test(QWidget):
def __init__(self):
super(Simple_Test,self).__init__() #使用super函数可以实现子类使用父类的方法
self.setWindowTitle("QMessageBox")
self.resize(400,100)
self.button_1 = QPushButton("Question",self)
self.button_2 = QPushButton("Information",self)
#连接信号和槽
self.button_1.clicked.connect(lambda:self.show_msg(self.button_1))
self.button_2.clicked.connect(lambda:self.show_msg(self.button_2))
self.layout = QVBoxLayout()
self.layout.addWidget(self.button_1)
self.layout.addWidget(self.button_2)
self.setLayout(self.layout)
def show_msg(self,button):
if button == self.button_1:
QMessageBox.question(self,"Question","Do you know it",QMessageBox.Yes|QMessageBox.No)
elif button == self.button_2:
QMessageBox.information(self,"Information","ok,you got it",QMessageBox.Ok)
if __name__ == "__main__":
app = QApplication(sys.argv)
test = Simple_Test()
test.show()
sys.exit(app.exec())
output:
汉化对话框
调用addButton方法传入中文字符串,确定按键要担任的角色。
import sys
from PyQt5.QtWidgets import QApplication,QWidget,QPushButton,QMessageBox
class Simple_Test(QWidget):
def __init__(self):
super(Simple_Test,self).__init__() #使用super函数可以实现子类使用父类的方法
self.button = QPushButton("Question",self)
self.button.clicked.connect(self.show_msg)
def show_msg(self,button):
msg = QMessageBox(self) #实例化一个QMessageBox对象
msg.setWindowTitle("Question")
msg.setText("Do you know it?")
msg.setIcon(QMessageBox.Question)
#调用addButton方法
msg.addButton("是",QMessageBox.YesRole)
msg.addButton("否",QMessageBox.NoRole)
msg.exec()
if msg.clickedButton().text() == "是":
self.close()
print("你很棒")
else:
self.close()
print("加油,再努力一下吧")
if __name__ == "__main__":
app = QApplication(sys.argv)
test = Simple_Test()
test.show()
sys.exit(app.exec())
ouput:
希望对大家的学习有帮助,感谢大家的支持。