[英]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.