汉化对话框的按钮
# -*- coding: utf-8 -*-
"""
Created on Sat May 9 14:46:56 2020
@author: Giyn
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
class Simple_Window(QWidget):
def __init__(self):
super(Simple_Window, self).__init__() # 使用super函数可以实现子类使用父类的方法
self.button = QPushButton("Question", self)
self.button.clicked.connect(self.show_msg_box)
def show_msg_box(self, button):
msg_box = QMessageBox(self) # 实例化一个QMessageBox对象
msg_box.setWindowTitle("Question") # 设置对话框的标题
msg_box.setText("Do you want to save it?") # 设置对话框的内容
msg_box.setIcon(QMessageBox.Question)
# 调用addButton方法传入字符串,确定按钮扮演的角色
msg_box.addButton("是", QMessageBox.YesRole)
msg_box.addButton("否", QMessageBox.NoRole)
msg_box.exec()
if msg_box.clickedButton().text() == "是": # clickedButton方法返回用户按下的按钮
self.close()
print("保存成功!")
else:
self.close()
print("退出程序!")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = Simple_Window()
window.show()
sys.exit(app.exec())
Output:
![](https://i-blog.csdnimg.cn/blog_migrate/9f04b7704672ea900a827f1751334fd2.png)
After clicking “是”:
![](https://i-blog.csdnimg.cn/blog_migrate/d1bffe9a0edb9b66ecdaf5f26e1961bd.png)
After clicking “否”:
![](https://i-blog.csdnimg.cn/blog_migrate/d8c54c85947921c7c35d53a8b4d8a7db.png)
QMessageBox对话框的图标参数:
QMessageBox.NoIcon
QMessageBox.Question
QMessageBox.Information
QMessageBox.Warning
QMessageBox.Critical
QMessageBox中常见的按钮角色:
QMessageBox::AcceptRole
− > -> −> O K OK OK
QMessageBox::RejectRole
− > -> −> C a n c e l Cancel Cancel
QMessageBox::YesRole
− > -> −> Y e s Yes Yes
QMessageBox::NoRole
− > -> −> N o No No
clickedButton
方法返回用户按下的按钮
Reference:https://study.163.com/course/courseLearn.htm?courseId=1208995818