0

我有这个用 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()

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

4

2 回答 2

0

只需传递TextBoxto的内容exec()

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

请注意,exec()不推荐使用执行代码。

于 2021-05-14T02:48:59.963 回答
0

这会读取文件的内容

OpenFileToRun.read()

使用 subprocess 它会给你很多选择。您可以使用 .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])
于 2021-05-14T03:35:37.210 回答