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

如何通过点击Tkinter按钮调用Python编写的test.exe程序?

调用外部EXE程序的Tkinter实现

当然可以,只需要修改原代码中调用外部程序的参数,指向你的test.exe完整路径即可。下面提供两种实用实现方式:

方式一:沿用os.system(简单直接)

修改后的完整代码,适配你的test.exe路径:

import sys
import os
from tkinter import *

window=Tk()

window.title("Running EXE Program")
window.geometry('550x200')

def run():
    # 用原始字符串避免反斜杠转义问题,也可以写成'C:\\Folder\\test.exe'
    os.system(r'C:\Folder\test.exe')
    # 如果路径包含空格,需要给路径套引号:os.system(r'"C:\My Folder\test.exe"')

btn = Button(window, text="Click Me", bg="black", fg="white", command=run)
btn.grid(column=0, row=0)

window.mainloop()

方式二:使用subprocess模块(推荐,功能更强大)

subprocess是Python官方推荐替代os.system的模块,支持获取程序输出、错误信息,灵活控制界面阻塞状态等:

import sys
import subprocess
from tkinter import *

window=Tk()

window.title("Running EXE Program")
window.geometry('550x200')

def run():
    # shell=True适配Windows下直接执行可执行文件的场景
    subprocess.run(r'C:\Folder\test.exe', shell=True)
    # 路径含空格的写法:subprocess.run(r'"C:\My Folder\test.exe"', shell=True)
    # 若不想阻塞Tkinter界面,改用subprocess.Popen即可:subprocess.Popen(r'C:\Folder\test.exe', shell=True)

btn = Button(window, text="Click Me", bg="black", fg="white", command=run)
btn.grid(column=0, row=0)

window.mainloop()

额外注意事项

  • 路径正确性:确保test.exe的路径完全准确,Windows路径中的反斜杠要么用原始字符串(r'路径'),要么用双反斜杠('C:\\Folder\\test.exe')
  • 空格处理:如果exe所在路径包含空格,必须用引号把整个路径包裹起来,比如r'"C:\Program Files\test.exe"'
  • 界面阻塞控制:os.system和subprocess.run默认会阻塞Tkinter界面直到exe执行完毕,若希望点击按钮后界面仍可操作,替换为subprocess.Popen即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:25:14