pyqt 取消后退出程序 打开文件对话框_PyQt对话框 - 按下按钮后如何退出?

这篇博客讲述了作者在开发一个使用PyQt4的小应用程序时遇到的问题,该程序是一个简单的Yes/No对话框,点击"Yes"按钮执行外部命令(例如'eject/dev/sr0'),但点击"Yes"后对话框并未自动关闭。为解决这个问题,作者提供了修改建议,即用一个包含多个语句的函数替换lambda表达式,使得在执行命令后同时关闭对话框。
摘要由CSDN通过智能技术生成

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)

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值