简体   繁体   中英

Open txt file through Tkinter GUI

I'm wondering how to open a file through a Tkinter GUI, example having a button in your interface that opens a .txt file. It doesn't matter if it loads into a textbox or if it opens in the text-editor just want it to open. Preferably to open in the text-editor.

def openInstruktion():
    f= open("instruktioner.txt")

instruktionBtn = Button(root, text='Spelinstruktioner', command=openInstruktion)
instruktionBtn.grid(row=6, column=0)

I've searched the web for some answer but most people use the menubar. I want it to open through the button posted above.

So if you want to do something to the file the operations will happen in function openInstruktion .

def openInstrucktion():
    f= open("instruktioner.txt")
    #t is a Text widget
    t.insert(1.0, f.read())

Or if you want to open it with an editor:

def openInstrucktion():
    os.system('emacs instrucktioner.txt')

If you want to open the file with the default program, you could use the os module:

def openInstruktion():
    from os import startfile
    startfile("c:\\path\\to\\file")

instruktionBtn = Button(root, text='Spelinstruktioner', command=openInstruktion)
instruktionBtn.grid(row=6, column=0)

or, if you want to open it with a specific program, try the subprocess module:

def openInstruktion():
    from subprocess import call
    call("notepad c:\\path\\to\\file")

instruktionBtn = Button(root, text='Spelinstruktioner', command=openInstruktion)
instruktionBtn.grid(row=6, column=0)

If you want to open it in a textbox however, you could do something like this:

file = open("c:\\path\\to\\file").read()
textbox.insert(0.0, file)

Your best bet would probably be to open it in the default editor (opening it with a different program may not be what people want and opening it in a textbox has poor graphics).

If you want to open the file in the default editor (it always best to use the default one only)

def openInstrucktion():
    os.system('start " " instruktioner.txt')
def help():
    readme = "F:\\yourpath\\readme.txt"
    os.startfile(readme)

just use this function , but first do import os at the top..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM