如何 运行 当前在 python tkinter 中打开的文件?

How to run currently opened file in python tkinter?

我用 python tkinter 编写了这个程序,它有一个文本框和一个菜单。菜单有两个选项,打开文件和 运行 文件。

打开文件可让您打开python 个文件并将文件内容写入文本框。 运行 文件会打开一个文件对话框,让您 select 一个 python 文件到 运行。

我试图做到这一点,当您按下 运行 文件按钮时,程序将 运行 当前打开的文件,而不是创建一个新的文件对话框,要求您 select 一个文件到 运行。但是,我 运行 在执行此操作时遇到了问题。

到目前为止,这是我的代码:

# Imports
from tkinter import *
from tkinter import filedialog


# Window
root = Tk()
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))


# Global OpenStatusName - used for finding name and status of opened file and use it for saving file and etc
global OpenFileStatusName
OpenFileStatusName = False


# Open File Function
def OpenFile(*args):
    # Ask user for which file they want to open
    FilePath = filedialog.askopenfilename(initialdir="C:/gui/", title="Open a File", filetypes=(("All Files", "*.*"), ("Text Files", "*.txt"), ("HTML Files", "*.html"), ("CSS Files", "*.css"),("JavaScript Files", "*.js"), ("Python Files", "*.py")))
    
    # Check to see if there is a file opened, then find the name and status of the file and use it in code for other things like saving a file and accessing it later
    if FilePath:
        global OpenFileStatusName
        OpenFileStatusName = FilePath
    
    # Delete Any Previous Text from the TextBox
    TextBox.delete("1.0", END)
    
    # Open File and Insert File Content into Editor
    FilePath = open(FilePath, 'r')
    FileContent = FilePath.read()
    TextBox.insert(END, FileContent)
    FilePath.close()


# Run Python Menu Options
def RunPythonFile():
    OpenFileToRun = filedialog.askopenfile(mode="r", title="Select Python File to Run")
    exec(OpenFileToRun.read())


# Main Frame for Placing the Text Box
MainFrame = Frame(root)
MainFrame.pack()


# Text Box
TextBox = Text(MainFrame, width=500, undo=True)
TextBox.pack(fill=BOTH)


# Menu Bar
MenuBar = Menu(root)
root.config(menu=MenuBar)


# File Option for Menu Bar
FileMenu = Menu(MenuBar, tearoff=False)
MenuBar.add_cascade(label="File", menu=FileMenu)
FileMenu.add_command(label="Open", command=OpenFile)
FileMenu.add_command(label="Run File", command=RunPythonFile)


# Mainloop
root.mainloop()

除了 RunPythonFile 函数中的 OpenFileToRun = filedialog.askopenfile(mode="r", title="Select Python File to Run") exec(OpenFileToRun.read()) 之外,还有什么我可以添加的,这样程序只会 运行 当前打开的文件吗?

只需将TextBox的内容传递给exec()即可:

# Run Python Menu Options
def RunPythonFile():
    exec(TextBox.get("1.0", "end-1c"))

请注意,不建议使用 exec() 来执行代码。

这会读取文件的内容

OpenFileToRun.read()

使用子流程会给你很多选择。您可以使用 .wait、subprocess.call 或 check_call 等。

import subprocess as sp

# Run Python Menu Options
def RunPythonFile():
    OpenFileToRun = filedialog.askopenfilename(initialdir="Path",title="Select Python File to Run",filetypes = (("python files","*.py"),("all files","*.*")))
    nextProg = sp.Popen(["python",OpenFileToRun])