Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python Tkinter中打开文件_Python_Tkinter - Fatal编程技术网

在Python Tkinter中打开文件

在Python Tkinter中打开文件,python,tkinter,Python,Tkinter,在tkinter中是否可以打开并运行任何文件? 我想通过单击应用程序中的按钮打开txt文件。 喜欢下面这张照片吗 有什么办法吗?你可以使用subprocess.Popen()或者如果它是一个txt文件,那么用f=file.open(“path/name.txt”、“r或w或a”)打开它,我不知道如何对你的案例有信心 import tkinter as tk def on_click(event): root.destroy() with open("somefile.py")

在tkinter中是否可以打开并运行任何文件? 我想通过单击应用程序中的按钮打开txt文件。 喜欢下面这张照片吗


有什么办法吗?

你可以使用subprocess.Popen()或者如果它是一个txt文件,那么用f=file.open(“path/name.txt”、“r或w或a”)打开它,我不知道如何对你的案例有信心

import tkinter as tk

def on_click(event):
    root.destroy()
    with open("somefile.py") as f:
        code = compile(f.read(), "/path/to/my/file.py", 'exec')
        exec(code, global_vars, local_vars)


root = tk.Tk()
button = tk.Button(root, text="Run")
button.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
button.bind("<Button-1>", on_click)
tk.mainloop()

使用此代码打开一个文件

标记为I的可能副本,因为唯一的区别是将其放入button的命令中。回答“是否可能”问题的最佳方法是亲自尝试并查看。如果它不起作用,那么你可以回来问一个问题。对不起,我指的不是这个,我指的是这个正在运行另一个python,但我想我指的不是这个。没有简单的跨平台方式来以你想要的方式运行文件。如果您在Windows上,则可以使用
os.startfile(文件名)
;如果您在unix上,您可以使用
os.system(“xdg打开%s”%filename)
,如果您在Mac上,您可以使用
os.system(“打开%s”%filename)
。如果你想在这些平台中的每一个平台上使用它,它将变得复杂得多。但是,无论您想做什么,都必须将其放入单击()时的
函数中。
def on_click(event):
    root.destroy()
    execfile("/path/to/my/file.py")
from Tkinter import *
from tkFileDialog import askopenfilename
def openfile():

   filename = askopenfilename(parent=root)
   f = open(filename)
   f.read()

root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=openfile)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

root.config(menu=menubar)
root.mainloop()