单击按钮时调用脚本

时间:2020-02-08 06:20:05

标签: python pyqt5

我有一个程序,这是它的简单思想。首先,我运行main_window.py,它将打开sub_window.py,此sub_window具有2个按钮Run和Stop。

单击运行按钮时,我需要运行hello.py脚本并关闭子窗口GUI,就像单击停止时一样,我需要停止hello.py脚本并关闭子窗口GUI。

我当前的代码给我“ NameError:未定义名称'Dialog'”错误。

这是main_window.py代码

public class MainActivity extends AppCompatActivity {
    private InterstitialAd mInterstitialAd;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
        if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {


            MobileAds.initialize(this,
                    "ca-app-pub-3940256099942544~3347551713");
            mInterstitialAd = new InterstitialAd(this);
            mInterstitialAd.setAdUnitId("ca-app-pub-3940255099942544/1033173712");
            mInterstitialAd.loadAd(new AdRequest.Builder().build());
            prepareAD();
            ScheduledExecutorService ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            ScheduledExecutorService.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mInterstitialAd.isLoaded()) {

                                mInterstitialAd.show();
                            } else {
                                Log.d("TAG", "Ad not loaded");
                            }
                            prepareAD();
                        }
                    });
                }
            }, 5, 5, TimeUnit.MINUTES);

        }else{
            Toast.makeText(getApplicationContext(), "No Internet Connection, please try again later...", Toast.LENGTH_LONG).show();

        }
    }

    public void prepareAD() {
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173212");
        mInterstitialAd.loadAd(new AdRequest.Builder().build());
    }

}

这是sub_window.py代码

from PyQt5 import QtCore, QtGui, QtWidgets
import sub_window

class Ui_MainWindow(object):

    def sub(self):
        self.subwin = QtWidgets.QDialog()
        self.ui =  sub_window.Ui_Dialog()
        self.ui.setupUi(self.subwin)  
        self.subwin.show()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(397, 157)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.btnClick = QtWidgets.QPushButton(self.centralwidget)
        self.btnClick.setGeometry(QtCore.QRect(100, 50, 161, 51))
        self.btnClick.setObjectName("btnClick")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)

        ################### Butten Event ##################################
        self.btnClick.clicked.connect(self.sub)


        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Main Window"))
        self.btnClick.setText(_translate("MainWindow", "Click"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

这是hello.py代码

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Dialog(object):

    def funRun(self):
        Dialog.hide()
        exec(open("hello.py").read())

    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(332, 108)
        self.btnRun = QtWidgets.QPushButton(Dialog)
        self.btnRun.setGeometry(QtCore.QRect(50, 40, 101, 31))
        self.btnRun.setObjectName("btnRun")
        self.btnStop = QtWidgets.QPushButton(Dialog)
        self.btnStop.setGeometry(QtCore.QRect(180, 40, 101, 31))
        self.btnStop.setObjectName("btnStop")

        self.retranslateUi(Dialog)

        ################### Butten Event ##################################
        self.btnRun.clicked.connect(self.funRun)

        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Sub Window"))
        self.btnRun.setText(_translate("Dialog", "Run"))
        self.btnStop.setText(_translate("Dialog", "Stop"))


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

1 个答案:

答案 0 :(得分:2)

首先,您不应该按照生成的文件和the docs的警告来修改pyuic生成的.py,因此必须通过再次运行pyuic命令来还原这些文件。

考虑到上述情况,那么必须在实现逻辑的位置创建一个main.py。另一方面,使用exec()被认为不是好习惯,因此在这种情况下,您必须修改“ hello.py”,以便将无限循环封装在函数中。您还必须记住,不能在同一GUI线程中执行无限循环,因此必须在辅助线程中执行它:

main.py

from PyQt5 import QtCore, QtGui, QtWidgets
from main_window import Ui_MainWindow
from sub_window import Ui_Dialog
import threading
from hello import task


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.dialog = Dialog()
        self.btnClick.clicked.connect(self.dialog.show)


class Dialog(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setupUi(self)
        self.btnRun.clicked.connect(self.run)

    @QtCore.pyqtSlot()
    def run(self):
        threading.Thread(target=task, daemon=True).start()
        self.hide()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

hello.py

import time


def task():
    while True:
        print("Hello")
        time.sleep(1)

如果无法修改hello.py或必须使用exec(),则必须创建一个执行该任务的函数:

main.py

from PyQt5 import QtCore, QtGui, QtWidgets
from main_window import Ui_MainWindow
from sub_window import Ui_Dialog
import threading


def task():
    with open("hello.py") as f:
        exec(f.read())


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)

        self.dialog = Dialog()
        self.btnClick.clicked.connect(self.dialog.show)


class Dialog(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setupUi(self)
        self.btnRun.clicked.connect(self.run)

    @QtCore.pyqtSlot()
    def run(self):
        threading.Thread(target=task, daemon=True).start()
        self.hide()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())