我是一个简单的文本编辑器程序。您可以单击另存为,然后您可以选择保存该文件的位置。但是,如果您单击保存按钮以保存到该文件,我会收到他的错误:
TypeError:强制转换为Unicode:需要字符串或缓冲区,找到文件
以下是保存并保存为代码的一部分。我有一个变量avalivle到所有fucntion(self.Saved):
def Save(self):
File = open(self.Saved,"w") --Where error occurs
if File is None:
return
self.Cont.insert(END,"<fg='" + self.FontColor + "'>")
self.Cont.insert(END,"<bg='" + self.BackgroundColor + "'>")
Content=self.Cont.get(1.0,END)
File.write(Content)
File.close()
def SaveAs(self):
File = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt")
if File is None:
return
self.Saved = File
self.Cont.insert(END,"<fg='" + self.FontColor + "'>")
self.Cont.insert(END,"<bg='" + self.BackgroundColor + "'>")
Content = self.Cont.get(1.0,END)
File.write(Content)
File.close()
答案 0 :(得分:0)
在self.Saved = None
中设置__init__
并执行
def Save(self):
if not self.Saved:
self.SaveAs()
else:
File = open(self.Saved,"w") # Where error occurs
if File is None:
return
self.Cont.insert(END,"<fg='" + self.FontColor + "'>")
self.Cont.insert(END,"<bg='" + self.BackgroundColor + "'>")
Content=self.Cont.get(1.0,END)
File.write(Content)
File.close()
编辑:使用asksaveasfilename
获取文件名
def SaveAs(self):
filename = tkFileDialog.asksaveasfilename(defaultextension=".txt")
if not filename:
return
self.Saved = filename
File = open(self.Saved,"w")
if File is None:
return
self.Cont.insert(END,"<fg='" + self.FontColor + "'>")
self.Cont.insert(END,"<bg='" + self.BackgroundColor + "'>")
Content = self.Cont.get(1.0,END)
File.write(Content)
File.close()