Python tkinter:使用一个按钮选择一个txt文件,使用另一个按钮打开并读取内容以字符串

时间:2018-11-01 04:23:16

标签: python python-3.x tkinter

我正在开发一个程序,该程序允许用户使用一个按钮选择文件:

    def select_file(self):
            filename = tkinter.filedialog.askopenfilename(initialdir=".")
            infile = open(filename, "r")

和另一个标记为计数发生的按钮,应将txt文件读入字符串以搜索用户输入的内容:

def count_occurrences(self):
    user_file = open(infile, "r")
    txt_file = user_file.read()

   # (omitted the code for counting occurrences for the sake of relevance)

我不确定问题出在哪个功能上,或者两者兼有。

单击“选择文件”按钮后,标签中会显示目录名称,但是当我在输入搜索文本后单击“出现次数”按钮时,出现错误:

“ user_file = open(filename,” r“)FileNotFoundError:[错误2]没有这样的文件或目录:

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

我不确定您的项目代码是什么,但她是解决方案的地方:

from tkinter import *
from tkinter import ttk, filedialog
#import io

class ReadFileApp:

    def __init__(self, master):

        self.label = ttk.Label(master, text = "How Read a File Content!")
        self.label.grid(row = 0, column = 0, columnspan = 2)

        ttk.Button(master, text = "Open File",
                   command = self.select_file).grid(row = 2, column = 0)

        ttk.Button(master, text = "Print the Content",
                   command = self.count_occurrences).grid(row = 2, column = 1)    

    def select_file(self):
            filename = filedialog.askopenfilename(initialdir=".")
            self.infile = open(filename, "r")
            #self.infile = io.TextIOWrapper(self.infile, encoding='utf8', newline='')
            print(self.infile.name)

    def count_occurrences(self):
        with open(self.infile.name, 'r') as myfile:
            txt_file=myfile.read().replace('\n', '')
        print(txt_file)

def main():              
    main = Tk()
    app = ReadFileApp(main)
    main.mainloop()

if __name__ == "__main__": main()

此代码应该可以正常工作。

您的问题是: 1.本地变量infile对其他功能不可见 2. filedialog函数返回io.TextWrapper类型,因此您需要通过调用infile.name

以字符串形式获取路径。