Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

python - PyQt dialog - How to make it quit after pressing a button?

Well, I'm writing a small PyQt4 app, it's just a single Yes/No dialog which has to execute an external command (e.g. 'eject /dev/sr0') and quit.

The app runs, it executes the command after pressing the "Yes" button, but I cannot make the dialog itself exit when executing the command.

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import subprocess
from PyQt4 import QtGui
from PyQt4 import QtCore
from subprocess import call
cmd = 'eject /dev/sr0'

class Example(QtGui.QWidget):

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

        self.initUI()

    def initUI(self):

        btn = QtGui.QPushButton('Yes', self)     
        btn.clicked.connect(lambda: os.system(cmd))
        btn.resize(180, 40)
        btn.move(20, 35)       

        qbtn = QtGui.QPushButton('No', self)
        qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        qbtn.resize(180, 40)
        qbtn.move(20, 80) 

        self.setWindowTitle('Test')    
        self.show()

def main():

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


if __name__ == '__main__':
    main()

Here is my code. When I click "Yes", it calls the 'eject /dev/sr0' command properly, but after that the dialog is still visible. I have to click "No" to close the app I would like it to close automatically when the command is executed. What should I add/modify?

question from:https://stackoverflow.com/questions/65864102/how-do-i-close-the-browser-window-automatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Replace lambda: os.system(cmd) with a function/method that has multiple statements.

def buttonClicked(self):
    os.system(cmd)
    QtCore.QCoreApplication.instance().quit()

...
    btn = QtGui.QPushButton('Yes', self)     
    btn.clicked.connect(self.buttonClicked)
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...