-2

Is there possible to open and run any file in tkinter? I want to open txt file by clicking a button in application. Like this picture below

Open File

Is there any way?

Dias
  • 1
  • 2
  • 5
  • 2
    Possible duplicate of [How do I execute a program from python? os.system fails due to spaces in path](http://stackoverflow.com/questions/204017/how-do-i-execute-a-program-from-python-os-system-fails-due-to-spaces-in-path) – Lafexlos Feb 18 '16 at 11:51
  • I flagged as such because the only difference is putting that into button's command. – Lafexlos Feb 18 '16 at 11:53
  • 1
    the best way to answer an "is it possible" question is to try it and see for yourself. If it doesn't work, _then_ you can come back and ask a question. – Bryan Oakley Feb 18 '16 at 13:19

3 Answers3

0

you could either use subprocess.Popen() or if it is a txt file, then open it with f = file.open("path/name.txt","r or w or a"), Iam not sure how to be confident with your case though

L_Pav
  • 281
  • 1
  • 3
  • 11
0
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()

This will put the button in the middle of the window, and when clicked, will run "/path/to/my/file.py". If you are using Python2, on_click() can be simplified to this:

def on_click(event):
    root.destroy()
    execfile("/path/to/my/file.py")
zondo
  • 19,901
  • 8
  • 44
  • 83
  • this one is running another python, but I guess not this one that I mean. – Dias Feb 18 '16 at 13:18
  • There is no simple cross-platform way to run a file in the way you want. If you are on Windows, you can use `os.startfile(filename)`; if you are on unix, you can use `os.system("xdg-open %s" % filename)`, if you are on Mac, you can use `os.system("open %s" % filename)`. If you want it on each of those platforms, it will be a lot more complicated. Whatever you want to do, though, you will have to put it in the `on_click()` function. – zondo Feb 18 '16 at 14:31
0
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()

use this code to open a file

Ashok Kumarkvm
  • 148
  • 2
  • 7