简体   繁体   English

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

[英]Python tkinter: use one button to select a txt file and another to open and read contents to string

I am working on a program that allows the user to select a file using one button: 我正在开发一个程序,该程序允许用户使用一个按钮选择文件:

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

and another button, labeled count occurrences, should read the txt file into a string to search for what the user entered: 另一个标记为计数发生的按钮应将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)

I am unsure which function the problem lies in or if it is both. 我不确定问题出在哪个功能上,或者两者兼而有之。

After clicking the "select file" button, a directory name shows in the label but when I click the "count occurrences" button after entering the search text, I get the error: 单击“选择文件”按钮之后,目录名称显示在标签中,但是当我在输入搜索文本后单击“出现次数”按钮时,出现错误:

"user_file = open(filename, "r") FileNotFoundError: [Errno 2] No such file or directory: '' “ user_file = open(文件名,“ r”)FileNotFoundError:[错误2]没有这样的文件或目录:”

Any help would be appreciated, thanks! 任何帮助,将不胜感激,谢谢!

I am not sure what is your project code, but her is the solution: 我不确定您的项目代码是什么,但是她是解决方案:

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

this code should work perfectly fine. 此代码应该可以正常工作。

your problem was: 1.the local variable infile is not visible to other functions 2.the filedialog function returns an io.TextWrapper type, so you need to get the path as a string by calling infile.name 您的问题是:1.本地变量infile对其他函数不可见2. filedialog函数返回io.TextWrapper类型,因此您需要通过调用infile.name以字符串形式获取路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 读取txt文件的内容并在Tkinter GUI Python中显示 - Read Contents of txt file and display in Tkinter GUI Python 使用带有参数/条目的 tkinter 按钮打开另一个 python 文件 - Open another python file using tkinter button with parameters/entry 打开文件按钮-Python Tkinter - Open File Button - Python Tkinter 如何使用 Python 将文件夹中的 all.txt 文件和 append 其内容读取到 one.txt 文件中? - How to read all .txt files in a folder and append its contents into one .txt file, using Python? Python / Tkinter - Select 并从另一个 function 单击按钮将所有文本内容复制到剪贴板 - Python / Tkinter - Select and copy all Text contents to clipboard on Button click from another function 读取 txt 文件并将内容添加到 Tkinter 列表框 Python - Reading txt file and adding the contents to a Tkinter Listbox Python Python Tkinter 文本小部件不显示 .txt 文件中的内容 - Python Tkinter Text Widget not displaying contents from .txt file 在 Tkinter Python 中销毁一个窗口并打开另一个窗口 - Destroy one window and open another in Tkinter Python 比较一个txt文件中的字符串与另一个txt文件中的字符串 - Compare string in one txt file to string in another Python3 Tkinter-使用按钮打开.py文件 - Python3 Tkinter - Open .py file with button
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM