我编写了我的程序,让它全部工作,我开始对它进行更改,因此它更有效率,我被告知要使用一个类,我以前从未使用过一个,我试图使用一个类,程序运行正常,直到你点击去,我可以看到为什么你得到这个错误,我认为它与两个''在第11行,但我不确定我应该把它放在那里。
#Imports
import tkinter
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
from tkinter import filedialog
import sys
class MyFileManager(object):
def __init__(self, filename='', save_filename=''):
self.filename = filename
self.save_filename = save_filename
def save_users_list(self, list_name):
with open(self.filename, 'r') as file:
users_list = [line.strip() for line in file.readLines()]
with open(self.save_filename, 'w') as file:
file.write('{} = {}'.format(list_name, str(users_list)))
def get_filename(self):
self.save_filename = askopenfilename(filetypes=(("Text files", "*.txt"),
("All files", "*.*")))
def get_save_file(self):
self.save_filename = asksaveasfilename(filetypes=(("Text files", "*.txt"),
("All files", "*.*")))
manager = MyFileManager()
#Window
window = tkinter.Tk()
window.title("Python List Maker")
window.geometry("300x170")
#Label
file_select_label = tkinter.Label(window, text="Please select your file:")
file_select_label.pack()
#Button
filename_button = tkinter.Button(window, text="Browse", command=manager.get_filename)
filename_button.pack()
#List Name
list_name_label = tkinter.Label(window,text="Please enter what you want to call the list:")
list_name_label.pack()
list_name = Entry(window)
list_name.pack()
#Save List
save_list_label = tkinter.Label(window,text="Please select where you want to save the list:")
save_list_label.pack()
save_filename_button = tkinter.Button(window, text="Browse", command=manager.get_save_file)
save_filename_button.pack()
#Go
go_button = tkinter.Button(window, text="Go!", command=lambda: manager.save_users_list(
list_name.get()))
go_button.pack()
#Main Loop
window.mainloop()
以下是我收到的错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1490, in __call__
return self.func(*args)
File "/home/ashleymoakes/Desktop/Learning Python/WIP/List Maker/List Maker - Re-Write.py", line 62, in <lambda>
list_name.get()))
File "/home/ashleymoakes/Desktop/Learning Python/WIP/List Maker/List Maker - Re-Write.py", line 17, in save_users_list
with open(self.filename, 'r') as file:
FileNotFoundError: [Errno 2] No such file or directory: ''
此外,如果它有助于我运行Python 3.3
答案 0 :(得分:2)
您的问题是您从未将self.filename
变量设置为空,因此python无法找到名为''
的文件。我猜您必须将get_filename()
更改为以下内容:
def get_filename(self):
self.filename = askopenfilename(filetypes=(("Text files", "*.txt"),
("All files", "*.*")))
^
variable name changed