我尝试使用PyQt4创建一个程序,提示用户回答问题。如果答案是正确的,则应出现答案正确的注释,并生成新问题。如果答案不正确,则应该打印出该行,然后再次提出相同的问题。一个工作的例子是:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import numpy as np
import time
class Window(QWidget):
def __init__(self,parent=None):
super(Window, self).__init__(parent)
self.lineEdit = QLineEdit()
self.textBrowser = QTextBrowser()
layout = QVBoxLayout()
layout.addWidget(self.textBrowser)
layout.addWidget(self.lineEdit)
self.setLayout(layout)
self.lineEdit.setDisabled(False)
self.go_outer()
def go_outer(self):
random_instance=["home","honey","micro"]
random_corresponding=["depot","well","soft"]
random_index=np.random.randint(0,3)
self.ret=random_instance[random_index]
self.corres=random_corresponding[random_index]
self.go()
def go(self):
self.textBrowser.append(self.ret)
self.lineEdit.returnPressed.connect(self.process)
def process(self):
userInput = self.lineEdit.text()
if userInput == self.corres:
self.textBrowser.append("Your answer is correct.")
self.textBrowser.update()
time.sleep(5)
self.textBrowser.clear()
self.go_outer()
else:
self.textBrowser.append("Your answer is incorrect. Please try again.")
self.textBrowser.update()
time.sleep(5)
self.lineEdit.clear()
self.textBrowser.clear()
self.go()
def run():
app=QApplication(sys.argv)
GUI=Window()
GUI.show()
sys.exit(app.exec_())
if __name__ == '__main__':
run()
问题是,它显示了从外部函数" get_text()"获得的文本,但没有显示"您的答案是正确的"或者"你的回答是不正确的。请再试一次。"
任何想法为什么会如此,以及如何解决它?
答案 0 :(得分:0)
您只需要将一次信号连接到插槽,因此您必须将其移动到构造函数。
另一个问题是睡眠功能不是GUI友好的,一个很好的选择是使用计时器,在这种情况下我们将使用QTimer.singleShot()
,我们将做一些小修改。
以上所有内容均在以下代码中实现:
class Window(QWidget):
def __init__(self,parent=None):
super(Window, self).__init__(parent)
self.lineEdit = QLineEdit()
self.textBrowser = QTextBrowser()
layout = QVBoxLayout()
layout.addWidget(self.textBrowser)
layout.addWidget(self.lineEdit)
self.setLayout(layout)
self.lineEdit.setDisabled(False)
self.go_outer()
self.lineEdit.returnPressed.connect(self.process)
def go_outer(self):
random_instance=["home","honey","micro"]
random_corresponding=["depot","well","soft"]
random_index=np.random.randint(0,3)
self.ret=random_instance[random_index]
self.corres=random_corresponding[random_index]
self.go()
def go(self):
self.textBrowser.clear()
self.lineEdit.setDisabled(False)
self.lineEdit.clear()
self.textBrowser.append(self.ret)
def process(self):
userInput = self.lineEdit.text()
self.lineEdit.setDisabled(True)
if userInput == self.corres:
self.textBrowser.append("Your answer is correct.")
QTimer.singleShot(5000, self.go_outer)
else:
self.textBrowser.append("Your answer is incorrect. Please try again.")
QTimer.singleShot(5000, self.go)