<p>你现在的结构似乎太复杂了。随机化问题选择要简单得多,而不是小部件本身。在</p>
<p>下面是一个简单的演示,演示如何做到:</p>
<pre><code>import sys, random
from PyQt4 import QtGui
class MultipleChoice(QtGui.QWidget):
def __init__(self, parent=None):
super(MultipleChoice, self).__init__(parent)
self.Questions = [
['What is the capital of Bhutan?',
'Thimphu', 'Bujumbura', 'Suva', 'Kigali'],
['What is the capital of Yemen?',
'Sana\'a', 'Malabo', 'Riyadh', 'Muscat'],
['What is the capital of Togo?',
'Lomé', 'Dakar', 'Abuja', 'Nouakchott'],
]
self.Questionum = QtGui.QLabel(self)
self.Questioninfo = QtGui.QLabel(self)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.Questionum)
layout.addWidget(self.Questioninfo)
self.buttonGroup = QtGui.QButtonGroup(self)
self.buttonGroup.buttonClicked.connect(self.handleChoice)
for index in range(4):
button = QtGui.QRadioButton(self)
self.buttonGroup.addButton(button, index)
layout.addWidget(button)
self.buttonNext = QtGui.QPushButton('Next', self)
self.buttonNext.clicked.connect(self.handleNext)
layout.addWidget(self.buttonNext)
self.index = -1
self.handleNext()
def handleNext(self):
self.index += 1
if self.index >= len(self.Questions):
self.index = 0
question = self.Questions[self.index]
self.Questionum.setText('Question %d:' % (self.index + 1))
self.Questioninfo.setText(question[0])
choices = question[1:]
random.shuffle(choices)
self.buttonGroup.setExclusive(False)
for index, choice in enumerate(choices):
button = self.buttonGroup.button(index)
button.setChecked(False)
button.setText(choice)
self.buttonGroup.setExclusive(True)
def handleChoice(self, button):
answer = self.Questions[self.index][1]
if button.text() == answer:
print('Right!')
else:
print('Wrong...')
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MultipleChoice()
window.show()
sys.exit(app.exec_())
</code></pre>