【问题标题】:How to run a python script with a tkinter button?如何使用 tkinter 按钮运行 python 脚本?
【发布时间】:2021-06-09 06:45:58
【问题描述】:

我有一个名为 main.py 的 python 文件,如下所示:

print('hello world')

我还有一个tkinkter_run.py 文件,看起来像这样:

import sys
import os
from tkinter import *
import main

window=Tk()

window.title("Running Python Script")
window.geometry('550x200')

def run():
    os.system('main.py')

btn = Button(window, text="Run your Code!", bg="blue", fg="white",command=run)
btn.grid(column=0, row=0)

window.mainloop()

当我运行我的tkinker_run.py 文件时,我确实得到了一个带有Run your Code! 按钮的窗口,但是当我单击该按钮并在 Visual Code 中查看我的终端时,我收到以下错误:

Hello World
'main.py' is not recognized as an internal or external command,
operable program or batch file.

所以似乎Hello World 在我点击Run your Code! 按钮之前就已经打印出来了。我不明白问题是什么......

【问题讨论】:

  • @martineau 你是什么意思?
  • main.pytkinkter_run.py在同一个目录吗?
  • @AST 是的。
  • @TangerCity 另外,Hello World 最初会被打印,因为您调用了import main。尝试使用os.system(os.path.abspath('main.py')),只是为了确保提供了正确的路径。
  • @AST 当我点击那个run the Code!按钮C:\data\EK\Desktop\Python is not recognized as an internal or external command, operable program or batch file.时我得到了这个

标签: python tkinter button main


【解决方案1】:

我的目录名称包含空格,大多数 shell 通过假设它们由空格分隔来拆分参数。所以解决办法是把包含脚本文件名的部分放在双引号之间。

os.system('python "c:\data\EK\Desktop\Python Microsoft Visual Studio\MM\main.py"')

成功了!

【讨论】:

  • 在我告诉过的 cmets 中,您提到它不起作用?无论如何,如果您不希望它阻止 GUI 的事件循环,请考虑使用 subprocess.Popen
  • 如果两个.py文件在同一个目录下,你可以从__file__中提取文件夹名称,并添加到main.py中,以确定运行时的完整路径。这将允许您避免将路径硬编码到代码中。
【解决方案2】:

这是因为 os.system 只接受命令而不接受文件名。

您可以替换此代码

os.system("main.py")

这样

os.system("python main.py")

【讨论】:

  • 我明白了:Hello World python: can't open file 'main.py': [Errno 2] No such file or directory 所以它似乎在我点击run the Code! 按钮之前再次打印出来
猜你喜欢
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-25
  • 1970-01-01
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多