PyQt dialog - How to make it quit after pressing a button?(PyQt 对话框 - 如何在按下按钮后退出?)
问题描述
好吧,我正在编写一个小型 PyQt4 应用程序,它只是一个是/否对话框,它必须执行外部命令(例如eject/dev/sr0")并退出.
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()
这是我的代码.当我单击是"时,它会正确调用eject/dev/sr0"命令,但此后对话框仍然可见.我必须单击否"关闭应用程序,我希望它在执行命令时自动关闭.我应该添加/修改什么?
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?
推荐答案
将 lambda: os.system(cmd)
替换为具有多个语句的函数/方法.
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 对话框 - 如何在按下按钮后退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!