PyQt4 - 单击Button时打开* .py文件

时间:2014-06-20 12:29:20

标签: python pyqt4 qtgui qtcore

单击“开始”按钮时,我想用pythonw.exe打开/运行* .py文件。谁能告诉我这是如何工作的?我没有在任何地方找到合适的功能。

import sys
from PyQt4 import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))

        self.setToolTip('This is a <b>QWidget</b> widget')

        btn1 = QtGui.QPushButton('Start', self)

        # OPENFILE SOMEHOW!!
        btn1.resize(btn1.sizeHint())
        btn1.move(20, 20)       



        qbtn = QtGui.QPushButton('Quit', self)
        qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(150, 20)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Python Script')    
        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

您可以使用subprocess.call。例如,当单击external.py时,此代码将运行Start

import sys
from PyQt4 import QtGui, QtCore
import subprocess

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()


    def run(self, path):
        subprocess.call(['pythonw',path])

    def initUI(self):

        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))

        self.setToolTip('This is a <b>QWidget</b> widget')

        btn1 = QtGui.QPushButton('Start', self)


        btn1.resize(btn1.sizeHint())
        btn1.move(20, 20)

        btn1.clicked.connect(lambda:self.run('external.py'))

        qbtn = QtGui.QPushButton('Quit', self)
        qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(150, 20)

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Python Script')

        #subprocess.call(['pythonw','3.py'])
        self.show()



def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()