如果我写入文本框的进程处于活动状态,我会编写此代码以弹出消息框。但是,如果我插入例如" chrome.exe"他弹出了很多消息框,因为在我的进程列表中有10个chrome.exe进程。与其他进程相同,如果只有一个进程,则只弹出一个进程。 我怎样才能解决这个问题?我写的代码是:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton,
QLineEdit, QMessageBox
import psutil
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 textbox - pythonspot.com'
self.left = 10
self.top = 10
self.width = 400
self.height = 140
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# Create textbox
self.textbox = QLineEdit(self)
self.textbox.setGeometry(QtCore.QRect(30, 40, 161, 31))
self.textbox.setObjectName("textEdit")
# Create a button in the window
self.button = QPushButton('Show text', self)
self.button.move(20, 80)
# connect button to function on_click
self.button.clicked.connect(self.on_click)
self.show()
def on_click(self):
textboxValue = self.textbox.text()
for pid in psutil.pids(): # Controlla se il processo è attivo
try:
listapid = psutil.Process(pid)
if listapid.name() == textboxValue:
QMessageBox.about(self, 'Process', 'Processo trovato')
self.textbox.setText("")
except:
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
答案 0 :(得分:0)
众所周知,chrome会创建多个进程,因此您可以获得该行为,可能的解决方案是在匹配时使用break
。
def on_click(self):
textboxValue = self.textbox.text()
for pid in psutil.pids(): # Controlla se il processo è attivo
try:
listapid = psutil.Process(pid)
if listapid.name() == textboxValue:
QMessageBox.about(self, 'Process', 'Processo trovato')
self.textbox.clear()
break
except:
pass