帮我生成一份可以实现诗词答题的Pyqt代码
时间: 2024-09-15 11:08:47 浏览: 60
实现一个基于PyQt的诗词答题应用,首先需要导入必要的库,如`PyQt5`、`random`等。下面是一个简单的示例代码框架,用于创建一个包含几首古诗的选择题:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QMessageBox
from PyQt5.QtCore import Qt
# 假设我们有这些古诗和选项
poems = {
"题目一": ["选项A", "选项B", "选项C"],
"题目二": [...], # 更多诗句和选项...
}
class QuizApp(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
self.setLayout(layout)
for i, (title, options) in enumerate(poems.items()):
quiz_question = QLabel(title)
quiz_question.setAlignment(Qt.AlignCenter)
buttons = []
for j, option in enumerate(options):
button = QPushButton(option)
button.clicked.connect(lambda _, opt=option: self.check_answer(i, opt))
buttons.append(button)
question_group = QWidget()
question_layout = QVBoxLayout(question_group)
question_layout.addWidget(quiz_question)
question_layout.addStretch() # 空白区域增加美观度
question_layout.addWidget(QHLine()) # 水平线分隔选项
for button in buttons:
question_layout.addWidget(button)
layout.addWidget(question_group)
start_button = QPushButton("开始")
start_button.clicked.connect(self.start_quiz)
layout.addWidget(start_button)
self.setWindowTitle('诗词答题')
self.show()
def check_answer(self, question_index, selected_option):
correct_answer = poems[question_index][0] # 假设第一个选项是正确答案
if selected_option == correct_answer:
QMessageBox.information(self, '恭喜', f'第 {question_index+1} 题答对了!')
else:
QMessageBox.warning(self, '错误', f'第 {question_index+1} 题答错了,正确答案是 {correct_answer}!')
def start_quiz(self):
pass # 这里可以根据实际情况添加随机出题或切换到下一题的功能
if __name__ == '__main__':
app = QApplication(sys.argv)
quiz_app = QuizApp()
sys.exit(app.exec_())
```
这个基础版本的应用包含了一个开始按钮,每点击一次会显示一个题目,并且当用户选择一个选项后,程序会检查是否正确并给出相应的提示。你需要根据实际的诗词数据填充`poems`字典,并完善`start_quiz`函数来实现自动出题功能。
阅读全文