Home > Software design >  How to use a python application (tkinter).exe to open a text file
How to use a python application (tkinter).exe to open a text file

Time:10-19

im a beginner at python and im trying to created a program using tkinter that view and edit text. i used pyinstaller to make an .exe file to view text, but when i used "open with" to a text file and select my text viewer program nothing shows.

then i noticed that how is my program supposed to open the file and display its contents. because originally i have this button "open file" that when clicked it, it will ask me what to open, but now that opening the file comes first before the program runs, i cannot click the button so my program does not know what to do. is there any way for my program to know what am i trying to open? do i have to import something?

thanks for the answer

from tkinter import *
from tkinter import filedialog

root=Tk()

def openfile():
    textname=filedialog.askopenfilename(title="Open File", filetypes=(("Text", "*.txt"), ("Python", "*.py"), ("Html", "*.html"), ("All Files", "*.*")))
    openedfile=open(textname,'r')
    content=openedfile.read()
    n_text.insert(END,content)
    openedfile.close()


n_text=Text(root, font=11, relief=FLAT)
n_text.pack()
btn=Button(root, text="open", command=openfile).pack()

root.mainloop()

CodePudding user response:

Not sure if I understood your question well. Do you need to know the path of the file you are opening?

    from os.path import split

    textname=filedialog.askopenfilename(title="Open File", filetypes=(("Text", "*.txt"), ("Python", "*.py"), ("Html", "*.html"), ("All Files", "*.*")))
    pathname = split(textname)
    #This print is just to show your path and filename
    print("path:", pathname[0], "file:",pathname[1])

Based on your comments I add a new answer it take the full path from arguments on scripts.

from tkinter import *
from tkinter import filedialog
import sys

root=Tk()

def openfile():
    textname=filedialog.askopenfilename(title="Open File", filetypes=(("Text", "*.txt"), ("Python", "*.py"), ("Html", "*.html"), ("All Files", "*.*")))
    openedfile=open(textname,'r')
    content=openedfile.read()
    n_text.insert(END,content)
    openedfile.close()


n_text=Text(root, font=11, relief=FLAT)
n_text.pack()
btn=Button(root, text="open", command=openfile).pack()

if len(sys.argv) == 2:
    openedfile=open(sys.argv[1],'r')
    content=openedfile.read()
    n_text.insert(END,content)
    openedfile.close()

root.mainloop()

I added the path in this format:

c:/Users/user/Python/pruebas.py "C:\Users\user\Desktop\text_file.txt"

  • Related