在python中集成GUI模块和后端代码模块

时间:2012-03-29 19:35:42

标签: python

我在python中工作。我在Qtdesigner中用模块Gui.Py创建了一个GUI。我有一个代码模块,我已经单独创建。现在有一个问题,我的代码模块中有一个方法可以在while循环中打印一段时间。我希望我的gui textbrowser显示在按钮点击事件中打印消息..我怎么能实时做到这一点.. 示例代码为:

Gui..py文件

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_Form(object):
def setupUi(self, Form):
    Form.setObjectName(_fromUtf8("Form"))
    Form.resize(400, 211)
    self.textBrowser = QtGui.QTextBrowser(Form)
    self.textBrowser.setGeometry(QtCore.QRect(140, 10, 256, 192))
    self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
    self.pushButton = QtGui.QPushButton(Form)
    self.pushButton.setGeometry(QtCore.QRect(20, 80, 97, 27))
    self.pushButton.setObjectName(_fromUtf8("pushButton"))

    self.retranslateUi(Form)
    QtCore.QMetaObject.connectSlotsByName(Form)

def retranslateUi(self, Form):
    Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
    self.pushButton.setText(QtGui.QApplication.translate("Form", "PushButton", None, QtGui.QApplication.UnicodeUTF8))


if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())

现在Sample.py

import time
class A:
def somefunction(self):
    i=0
    while i<100:
        print str(i)
        i+=1
        time.sleep(2)

if __name__=='__main__':
p=A()
p.somefunction()

请帮帮我, 谢谢

2 个答案:

答案 0 :(得分:0)

不要让somefunction直接打印结果,而是将结果yield发送给调用者。调用者可以逐个将字符串添加到GUI中。

但是,如果您的结果需要花费很长时间才能生成,就像使用任意sleep函数一样,您将阻止大多数GUI响应事件所需的消息循环。在这种情况下,您可以将其卸载到另一个线程,将结果传递回GUI线程以供显示。

答案 1 :(得分:0)

如果您希望将print语句显示在QTextBrowser中,那么您正在考虑连接一些插槽和信号。你可以在QtDesigner中做到这一点。

如果是这种情况,那么你应该看一下QTimer

p = A()
timer = QTimer() #Form as parent??
timer.timeout.connect(p.somefunc)  #different somefunc without the sleep thing
timer.start(2000)    # actually starts on app.exec_()
相关问题