使用pyqt5写一个按钮 按钮里面为确认
时间: 2024-05-09 20:18:02 浏览: 9
可以的,以下是使用 PyQT5 编写一个简单的确认按钮的代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn = QPushButton('确认', self)
btn.move(50, 50)
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('确认按钮')
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
这个代码可以创建一个窗口和一个简单的确认按钮。
相关问题
pyqt5点击按钮弹出确定按钮
你可以使用 QMessageBox 来实现这个功能,以下是示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Example')
button = QPushButton('Click me', self)
button.move(100, 100)
button.clicked.connect(self.showDialog)
self.show()
def showDialog(self):
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Information)
msgBox.setText('Button clicked')
msgBox.setStandardButtons(QMessageBox.Ok)
msgBox.exec_()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
在这个示例中,我们创建了一个按钮,当用户点击按钮时,会弹出一个 QMessageBox 对话框,显示 "Button clicked" 文本,并在对话框上显示一个 "确定" 按钮。
pyQT5实现:创建按钮,按下按钮会弹出一个选项卡弹窗,用于选择是否继续运行
以下是一个实现上述功能的pyQT5代码:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QTabWidget, QVBoxLayout, QDialog, QLabel, QHBoxLayout
import sys
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# 创建一个按钮
self.button = QPushButton('点击我', self)
self.button.move(50, 50)
self.button.clicked.connect(self.show_dialog)
def show_dialog(self):
# 创建一个选项卡弹窗
dialog = QDialog(self)
dialog.setWindowTitle('是否继续运行')
dialog_layout = QVBoxLayout()
# 创建选项卡
tab_widget = QTabWidget()
tab1 = QWidget()
tab2 = QWidget()
tab_widget.addTab(tab1, '是')
tab_widget.addTab(tab2, '否')
# 在第一个选项卡中添加标签和按钮
tab1_layout = QHBoxLayout()
tab1_label = QLabel('您确定要继续运行吗?')
tab1_layout.addWidget(tab1_label)
tab1_button = QPushButton('确定')
tab1_button.clicked.connect(dialog.accept)
tab1_layout.addWidget(tab1_button)
tab1.setLayout(tab1_layout)
# 在第二个选项卡中添加标签和按钮
tab2_layout = QHBoxLayout()
tab2_label = QLabel('您确定要停止运行吗?')
tab2_layout.addWidget(tab2_label)
tab2_button = QPushButton('确定')
tab2_button.clicked.connect(dialog.reject)
tab2_layout.addWidget(tab2_button)
tab2.setLayout(tab2_layout)
# 将选项卡添加到弹窗中
dialog_layout.addWidget(tab_widget)
dialog.setLayout(dialog_layout)
# 显示弹窗
if dialog.exec_() == QDialog.Accepted:
print('开始运行')
else:
print('停止运行')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.setGeometry(100, 100, 300, 200)
window.show()
sys.exit(app.exec_())
```
运行代码,点击按钮将会弹出一个选项卡弹窗,用户可以选择是否继续运行。选择“是”并点击“确定”按钮将会在控制台输出“开始运行”,选择“否”并点击“确定”按钮将会在控制台输出“停止运行”。