如何在pyqt设置好的按键,点击按键关闭运行已经调用的eye.py文件
import subprocess
class InterfaceWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow_inter()
self.ui.setupUi(self)
self.setWindowFlag(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground
self.ui.pushButton_open.clicked.connect(self.open_eye)
def open_eye(self):
subprocess.Popen(['python', 'eye.py'])
按键名称是pushButton——close
import sys
import subprocess
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class InterfaceWindow(QMainWindow):
def __init__(self):
super().__init__()
self.ui = Ui_MainWindow_inter()
self.ui.setupUi(self)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.ui.pushButton_open.clicked.connect(self.open_eye)
def open_eye(self):
self.kill_other_process('eye.py') # 使用subprocess库调用另一个Python进程执行eye.py脚本
if __name__ == '__main__':
app = QApplication(sys.argv)
window = InterfaceWindow()
window.show()
sys.exit(app.exec_())
2种方式
1.保存好进程句柄,你现在一旦运行完open_eye,句柄被丢弃了,你保存好句柄才能根据句柄去kill它
2.如果你能确保这个eye只会由你的程序调用,而且每次只会调用一个,那么可以遍历进程列表,查找eye进程,杀死
不要用subprocess,换成QProcess试试
import sys
import subprocess
from PyQt5.QtCore import QProcess
from PyQt5.QtWidgets import (QApplication, QMessageBox, QMainWindow, QPushButton)
class InterfaceWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建 QPushButton 实例并设置它的文本和父组件
self.closeButton = QPushButton('关闭程序', self)
# 把它移动到程序窗口中间。大小可以自行调整
self.closeButton.setGeometry(100, 100, 200, 50)
# 把 clicked 信号绑定到 stopProcess 方法上。
self.closeButton.clicked.connect(self.stopProcess)
# 创建 QProcess 实例,用于执行外部进程
self.process = QProcess(self)
# 执行外部 Python 脚本。shell=False 表示执行的是普通命令
self.process.start('python eye.py', shell=False)
def stopProcess(self):
# 终止执行中的进程
self.process.kill()
def closeEvent(self, event):
# 终止外部进程并退出窗口程序
self.process.kill()
event.accept()
if __name__ == '__main__':
# 创建 QApplication 实例
app = QApplication(sys.argv)
# 创建 InterfaceWindow 实例并显示主窗口
window = InterfaceWindow()
window.show()
# 进入 qt 主循环并等待退出
sys.exit(app.exec_())
核心代码:
在 def setupUi(self, MainWindow):最后一行加上self.toolButton.clicked.connect(self.msg)
然后在加一个成员函数msg即可
################button按钮点击事件回调函数################
self.toolButton.clicked.connect(self.msg)
def msg(self, Filepath):
m = QtWidgets.QFileDialog.getExistingDirectory(None, "选取文件夹", "C:/") # 起始路径
self.lineEdit_3.setText(m)