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

如何从Tkinter脚本运行外部Python脚本并实现进程通信?

问题解决与代码修正

1. 修复subprocess调用错误(避免修改test.py)

你的代码里dobot_COM_port方法存在两个关键错误:

  • 使用open(self.source,'w+')打开test.py,w+模式会清空原文件内容,这就是test.py被修改的核心原因;
  • 错误调用了Linux系统的["ls","-all"]命令,完全没有执行test.py脚本。

修正后的dobot_COM_port方法:

def dobot_COM_port(self): 
    self.source ='C:/Users/ching/OneDrive/Desktop/DobotGUI/test.py'
    # 调用Python解释器运行test.py,输出直接打印到终端,进程与GUI并行运行
    self.process_run_parallel = Popen(
        ["python", self.source], 
        stdout=None,  # 输出指向终端
        stderr=PIPE,
        stdin=PIPE,  # 开启输入管道用于后续传参
        text=True,
        start_new_session=True
    )

2. 实现脚本间通信与参数传递

原test.py是一次性执行脚本,运行后直接退出,无法接收后续指令。需要将其修改为持续运行的监听型脚本,通过标准输入接收Tkinter发送的参数。

修改后的test.py代码

让脚本保持运行状态,实时处理输入指令:

import sys

print("welcome")
# 持续监听标准输入,等待接收参数
for line in sys.stdin:
    line = line.strip()
    if not line:
        continue
    try:
        # 解析输入的指令格式(如"n=2")
        key, value = line.split("=")
        if key == "n":
            n = int(value)
            if n > 1:
                print("hi")
    except Exception:
        print("无效指令,请输入类似'n=数字'的格式")

修改Tkinter的「Home Cabliration」按钮逻辑

在button_1_clicked方法中,通过子进程的输入管道发送参数:

def button_1_clicked(self): 
    # 检查test.py进程是否已启动且正在运行
    if hasattr(self, 'process_run_parallel') and self.process_run_parallel.poll() is None:
        # 向test.py发送n=2的指令,末尾加换行符触发读取
        self.process_run_parallel.stdin.write("n=2\n")
        self.process_run_parallel.stdin.flush()  # 强制发送缓存数据
    else:
        print("请先点击「Connecting Dobot」启动test.py")
    print("button 1 click ")

额外优化建议

  • 如果需要在Tkinter界面中显示test.py的输出,可以将stdout=PIPE,然后通过after方法定时读取子进程的输出并更新到GUI标签;
  • 可以添加进程状态检查,避免重复启动test.py;
  • Windows系统中如果Python路径未加入环境变量,需替换"python"为完整路径(如"C:/Python39/python.exe")。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:15:48