8

我正在尝试制作一个可以打开文件的 Tkinter 程序。到目前为止,它打开了一个 tk 窗口,该窗口有一个选项,显示文件,然后是一个下拉菜单,当您单击它时显示打开,它会打开一个文件窗口,但我不知道如何实际打开该文件

这是我正在尝试的代码:

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()

这是窗口的样子

4

2 回答 2

17

当您打开文件时,您已经打开了文件f = open(filename)。要将文件的内容打印到控制台,您可以执行print f.read(). 或逐行浏览文件并打印内容,例如

for line in f:
    print line

这是一个如何打开文件并在 UI 上打印其内容的示例。我发现这个例子很有帮助,它准确地显示了你想要的:

from Tkinter import Frame, Tk, BOTH, Text, Menu, END
import 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 text


def main():

    root = Tk()
    ex = Example(root)
    root.geometry("300x250+300+300")
    root.mainloop()  


if __name__ == '__main__':
    main()  

资料来源:http: //zetcode.com/tkinter/dialogs/

于 2013-05-08T02:44:57.237 回答
0
import tkinter as tk

from 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()
于 2020-06-28T15:55:18.737 回答