如何在我们的python GUI中使用filedialog.askopenfile打开文本文件

时间:2018-06-27 07:22:38

标签: python tkinter

    #function to open the file
    import tkinter as tk
    from tkinter.scrolledtext import ScrolledText
    from tkinter import filedialog
    root = tk.Tk()
    textPad = ScrolledText(root)
        def open_command():
            file = filedialog.askopenfile(parent=root,mode='rt',title='Select a file')
            if file != None:
                contents = file.read()
                textPad.insert('1.0',contents)
                file.close()

我想知道如何将已经阅读的内容插入到GUI中。

1 个答案:

答案 0 :(得分:0)

您是否已将滚动文本放置在GUI中?我添加了一个pack()open_command()调用,您的代码对我有用。

import tkinter as tk
from tkinter.scrolledtext import ScrolledText
from tkinter import filedialog


root = tk.Tk()
textPad = ScrolledText(root)
textPad.pack()


def open_command():
    file = filedialog.askopenfile(parent=root,mode='rt',title='Select a file')
    if file != None:
        contents = file.read()
        textPad.insert('1.0',contents)
        file.close()

open_command()
root.mainloop()

enter image description here