You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PyQt5按钮点击触发Python脚本执行?

在PyQt5中实现点击按钮运行指定脚本的功能

Hey there! Let's get those buttons to run your target scripts when clicked. Using Python's subprocess module (ideal for spawning external processes) and extending your existing code, here's a straightforward solution:

Complete Modified Code

import sys
import subprocess
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication

class AutoTestWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn1 = QPushButton("Test № 1 ", self)
        btn1.move(30, 50)
        btn2 = QPushButton("Test № 2", self)
        btn2.move(150, 50)

        btn1.clicked.connect(self.buttonClicked)
        btn2.clicked.connect(self.buttonClicked)

        self.statusBar()
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Script Runner')
        self.show()

    def buttonClicked(self):
        # Get the button that triggered the click event
        sender_button = self.sender()
        
        # Map button text to corresponding script paths
        if sender_button.text() == "Test № 1 ":
            self.run_script("path/to/your/test_script_1.py")
        elif sender_button.text() == "Test № 2":
            self.run_script("path/to/your/test_script_2.py")

    def run_script(self, script_path):
        try:
            # Use the current Python interpreter to run the script
            # Capture output to show feedback in the status bar
            run_result = subprocess.run(
                [sys.executable, script_path],
                capture_output=True,
                text=True,
                check=True
            )
            # Show success feedback (truncate long output for readability)
            self.statusBar().showMessage(f"Success! Output: {run_result.stdout[:50]}...")
        except subprocess.CalledProcessError as err:
            # Show error if script exits with non-zero code
            self.statusBar().showMessage(f"Script failed: {err.stderr[:50]}...")
        except FileNotFoundError:
            # Handle missing script file
            self.statusBar().showMessage("Error: Script file not found!")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = AutoTestWindow()
    sys.exit(app.exec_())

Key Details Explained

  • subprocess.run(): This is the recommended way to run external commands in Python 3.5+. Using sys.executable ensures we use the same Python interpreter that's running your PyQt app, avoiding environment mismatch issues.
  • self.sender(): This method lets us identify which button was clicked, so we can map each button to its specific script.
  • Status Bar Feedback: The status bar gives immediate visual feedback about whether the script ran successfully, failed, or was missing.
  • Error Handling: We catch common issues like missing files and script runtime errors to make the app more robust.

Bonus: For Long-Running Scripts

If your scripts take time to execute, use subprocess.Popen instead of subprocess.run() to avoid freezing the UI:

def run_script(self, script_path):
    try:
        # Run script in the background without blocking the UI
        subprocess.Popen(
            [sys.executable, script_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
        self.statusBar().showMessage("Script started in background!")
    except FileNotFoundError:
        self.statusBar().showMessage("Error: Script file not found!")

内容的提问来源于stack exchange,提问作者Alex Nikitin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:16:14