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

问题描述

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

打开文件让你打开python文件并将文件内容写入文本框。运行文件会打开一个文件对话框,让您选择要运行的 python 文件

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

这是我目前的代码

# 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])