【问题标题】:How to link PyQt4 script button to activate another script?如何链接 PyQt4 脚本按钮以激活另一个脚本?
【发布时间】:2013-09-03 11:03:51
【问题描述】:

我正在尝试为我的程序实现 GUI,到目前为止,我使用 Qt4 设计器创建了基本 GUI 并对其进行了转换,但我不知道如何链接“确定”按钮以在终端中启动我的主脚本,还有一个框,我可以在其中输入一些随机数,我想将这些随机数与我的主脚本一起发送。假设一旦我启动 PyQt4 脚本并输入以下数字“123456”并按“确定”按钮,将打开一个终端窗口(archlinux),我的主脚本将与这些数字一起执行(我的主脚本称为 dd.py)。这是需要编辑的 PyQt4 代码:

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(400, 79)
        self.buttonBox = QtGui.QDialogButtonBox(Dialog)
        self.buttonBox.setGeometry(QtCore.QRect(50, 30, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.lineEdit = QtGui.QLineEdit(Dialog)
        self.lineEdit.setGeometry(QtCore.QRect(10, 30, 161, 31))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

        self.retranslateUi(Dialog)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
        QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

【问题讨论】:

    标签: python linux qt4 pyqt4


    【解决方案1】:

    在你的主脚本中,你需要让它接受参数。一个非常简单的方法是这样做:

    # dd.py
    import sys
    def main(arg):
        # do something here
        print arg
    
    if __name__ == "__main__":
        arg = sys.argv[1]
        main(arg)
    

    然后在您的 GUI 中,您将使用 subprocess 模块来调用您的主脚本并传递参数。所以在你的按钮的事件处理程序中,你会做这样的事情:

    subprocess.Popen("/path/to/dd.py", arg)
    

    如果您需要能够将开关或标志与参数一起传递,您应该阅读 argparse 或 optparse,具体取决于您使用的 Python 版本。

    【讨论】:

    • 谢谢迈克,感谢您阅读我的信息并帮助了我。爱你,你的网站也将永远在我的浏览器中添加书签:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 2017-01-22
    • 2016-04-08
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多