Opening File (Tkinter) Opening File (Tkinter) tkinter tkinter

Opening File (Tkinter)


You have already opened the file when you did f = open(filename).To print the contents of the file to the console, you could do print f.read().Or go through the file line by line & print the contents like

for line in f:    print line

Here is an example of how to open a file and print it's contents on the UI.I found this example to be helpful and it shows exactly what you want:

from Tkinter import Frame, Tk, BOTH, Text, Menu, ENDimport tkFileDialog class Example(Frame):    def __init__(self, parent):        Frame.__init__(self, parent)           self.parent = parent                self.initUI()    def initUI(self):        self.parent.title("File dialog")        self.pack(fill=BOTH, expand=1)        menubar = Menu(self.parent)        self.parent.config(menu=menubar)        fileMenu = Menu(menubar)        fileMenu.add_command(label="Open", command=self.onOpen)        menubar.add_cascade(label="File", menu=fileMenu)                self.txt = Text(self)        self.txt.pack(fill=BOTH, expand=1)    def onOpen(self):        ftypes = [('Python files', '*.py'), ('All files', '*')]        dlg = tkFileDialog.Open(self, filetypes = ftypes)        fl = dlg.show()        if fl != '':            text = self.readFile(fl)            self.txt.insert(END, text)    def readFile(self, filename):        f = open(filename, "r")        text = f.read()        return textdef main():    root = Tk()    ex = Example(root)    root.geometry("300x250+300+300")    root.mainloop()  if __name__ == '__main__':    main()  

Source: http://zetcode.com/tkinter/dialogs/


import tkinter as tkfrom os import *root = tk.Tk()root.title("Open file")os_str_var = tk.StringVar(root)def get_value_os():    try:        print(os_str_var.get())        tk.Label(root,text=f"{os_str_var.get()}").pack()        get_os_input = os_str_var.get()        startfile(f"{get_os_input}")        tk.Label(root, text=f"Good News! The system can find the path({get_os_input})         specified. ").pack()        print(f"Good News! The system can find the path({get_os_input}) specified. ")        return get_os_input    except:        tk.Label(root,text="The system cannot find the path specified. ").pack()        print("The system cannot find the path specified. ")os_entry = tk.Entry(root,textvariable=os_str_var).pack()os_button = tk.Button(root,text="Open",command=get_value_os).pack()root.mainloop()