按下按钮后如何退出

按下按钮后如何退出

本文介绍了PyQt对话框 - 按下按钮后如何退出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我正在写一个小的PyQt4应用程序,它只是一个单/双对话框,它必须执行一个外部命令(例如'eject / dev / sr0')并退出。



应用程序运行后,按是按钮执行命令,但执行该命令时不能使对话框退出。

 #!/ usr / bin / python 
# - * - 编码:utf-8 - * -

import sys
import os
import子进程
从PyQt4导入QtGui
从PyQt4导入QtCore
从子进程导入调用
cmd ='eject / dev / sr0'

类示例(QtGui.QWidget):

def __init __(self):
super(Example,self).__ init __()

self.initUI()

def initUI(self):

btn = QtGui.QPushButton('是',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_())


如果__name__ =='__main__':
main()

这是我的代码。当我单击是时,它正确地调用'eject / dev / sr0'命令,然后对话框仍然可见。我必须单击否关闭应用程序,我希望它在执行命令时自动关闭。我应该添加/修改?

解决方案

替换 lambda:os.system(cmd)具有多个语句的函数/方法。

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

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


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?

解决方案

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)
...

这篇关于PyQt对话框 - 按下按钮后如何退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 11:46