【问题标题】:Python tkinter: use one button to select a txt file and another to open and read contents to stringPython tkinter:使用一个按钮选择一个txt文件,另一个按钮打开并读取内容到字符串
【发布时间】:2019-04-05 07:37:21
【问题描述】:

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

    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: [Errno 2] 没有这样的文件或目录:''

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

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案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获取路径为字符串

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2012-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-24
      相关资源
      最近更新 更多