我有这个用 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 函数中,还有什么可以让程序只运行当前打开的文件吗?