简体   繁体   中英

importing simple program using pyqt4 and python

from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, \
        QLabel, QVBoxLayout, QWidget
from PyQt4 import QtGui
import sys

import subprocess

class MainWindow1(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent) 
        button = QPushButton('NotePad')

        label = QLabel('MainWindow1')

        centralWidget = QWidget()
        vbox = QVBoxLayout(centralWidget)
        vbox.addWidget(label)
        vbox.addWidget(button)
        self.setCentralWidget(centralWidget)

        button.clicked.connect(self.LaunchNotepad)

    # Some code here - including import subprocess
    def LaunchNotepad(self):

        returncode = subprocess.call(['python', 'notepad.py'])




if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainwindow1 = MainWindow1()
    mainwindow1.show()
    sys.exit(app.exec_())

that code creates a main window with a button, when i press the button i would like it to import my file called "notepad", (I think it does) however it opens it and closes it straight away. I need to be able to use the program notepad until i close it in which case it should revert back to the original window. Eventually i will have 3 or 4 buttons importing 3 or 4 different programs

I dont think there is an error in notepad because when i only have the statement "import notepad" it runs perfectly

note: the notepad file is just a simple text program (much like the "notepad" program on windows pcs)

thanks in advance

edit here is note pad code:

import sys
import os
import datetime as dt
from PyQt4 import QtGui
from PyQt4 import *


class Notepad(QtGui.QMainWindow):
    def __init__(self):
        super(Notepad, self).__init__()
        self.initUI()






    def initUI(self):
        newAction = QtGui.QAction('New', self)
        newAction.setShortcut('Ctrl+N')
        newAction.setStatusTip('Create new file')
        newAction.triggered.connect(self.newFile)  
        saveAction = QtGui.QAction('Save', self)
        saveAction.setShortcut('Ctrl+S')
        saveAction.setStatusTip('Save current file')
        saveAction.triggered.connect(self.saveFile)
        openAction = QtGui.QAction('Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open a file')
        openAction.triggered.connect(self.openFile)

        closeAction = QtGui.QAction('Close', self)
        closeAction.setShortcut('Ctrl+Q')
        closeAction.setStatusTip('Close Notepad')
        closeAction.triggered.connect(self.close)
        menubar = self.menuBar()

        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(newAction)
        fileMenu.addAction(saveAction)
        fileMenu.addAction(openAction)
        fileMenu.addAction(closeAction)

        #help menu
        helpMenu = menubar.addMenu('&Help')
        aboutAction = QtGui.QAction('About', self)
        aboutAction.setShortcut('Ctrl+A')
        aboutAction.setStatusTip('About')
        helpMenu.addAction(aboutAction)
        aboutAction.triggered.connect(self.about) 

        self.text = QtGui.QTextEdit(self)

        self.setCentralWidget(self.text)
        self.setGeometry(300,300,300,300)
        self.setWindowTitle('Notepad')


        self.show()
        self.statusBar()










    def newFile(self):
        self.text.clear()

    def saveFile(self):
        filename = QtGui.QFileDialog.getSaveFileName(self, 'Save File', os.getenv('HOME'))
        f = open(filename, 'w')
        filedata = self.text.toPlainText()
        f.write(filedata)
        f.close()

    def openFile(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))
        f = open(filename, 'r')
        filedata = f.read()
        self.text.setText(filedata)
        f.close()

        self.setGeometry(300,300,300,300)
        self.setWindowTitle('Notepad')
    self.show()
    def closeEvent(self, event):


        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes | 
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
    def about(self, event):
        reply = QtGui.QMessageBox.question(self, 'About Task Manager',
            "This is a notepad todo list program written by craig murch")


        return Notepad



if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    notepad = Notepad()

    sys.exit(app.exec_())

EDIT: The edited code above now does want i want it to do however it loads the cmd as well which i dont want to, how do i stop it loading the cmd?

Well, in your Notepad code you have

sys.exit(app.exec_())

This will close the entire process . So if you're importing it from your parent window then yeah, it should be closing your application.

Also, regardless of which GUI framework you use it's always a bad idea to mix mainloops in the same process. Instead, you should use subprocess to call your other application:

# Some code here - including import subprocess
import os
def LaunchNotepad(self):
    self.DoSomething() #Or whatever you want to do before your program launches
    returncode = subprocess.call(['pythonw', 'notepad.py'],
                                 stdout=open(os.devnull, 'w'),
                                 stderr=open(os.devnull, 'w'))
    self.ShowMe() #Won't run until notepad finishes
    if not returncode:
        self.ShowError("Notepad exited abnormally!")

That's a pretty basic example of what you could do.

at first glance i can't say that having this in a class definition won't work:

app = QtGui.QApplication(sys.argv)
notepad = Notepad()

sys.exit(app.exec_())

that's something you do guarded by

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    notepad = Notepad()
    notepad.show()  # call show here
    sys.exit(app.exec_())

not as part of class definition.

and having self.show() within initUI is not optimal either, a gui object shouldn't show itself per default, that makes no sense if you want to instantiate a component and then add it to another.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM