Python 3.5 Tkinter如何将dict保存到文件中



所以我的问题是,我正在运行一个程序,一旦它完成了基本功能,就会出现一个弹出框,询问用户是否要保存文件,如果"是",则会出现一个保存对话框。因为我保存的数据是dict值,所以我从tkinter收到一个Error。当我读到dict可以保存到某个地方时,我曾试图使用".csv"扩展名作为保存点,但我要么走错了路,要么我的代码中有问题。

更新的代码和解释如下

原始代码片段:

def flag_detection():
total_count = Counter(traffic_light)
total_count.keys()
for key, value in total_count.items():
EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')
file_opt = options = {}
options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
options['initialfile'] = 'myfile.csv'
if EWT == 'yes':
savename = asksaveasfile(file_opt, defaultextension=".csv")
savename.write(key, ':', value)

错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:UsersLewis CollinsAppDataLocalProgramsPythonPython35-32libtkinter__init__.py", line 1550, in __call__
return self.func(*args)
File "C:/Users/Lewis Collins/PycharmProjects/program_06.01.17/Home.py", line 108, in run_language_model
main.flag_detection()
File "C:UsersLewis CollinsPycharmProjectsprogram_06.01.17main_codemain.py", line 179, in flag_detection
savename = asksaveasfile(file_opt, defaultextension=".csv")
File "C:UsersLewis CollinsAppDataLocalProgramsPythonPython35-32libtkinterfiledialog.py", line 423, in asksaveasfile
return open(filename, mode)
TypeError: open() argument 2 must be str, not dict

由于Tkinter反驳说它无法将dict保存到文件中,我尝试了以下将dict转换为str的解决方案,这也导致了问题

函数的代码段试图转换为tkinter:的str

def flag_detection():

total_count = Counter(traffic_light)
total_count.keys()
for key, value in str(total_count.items()):
EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')
file_opt = options = {}
options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
options['initialfile'] = 'myfile.csv'
if EWT == 'yes':
savename = asksaveasfile(file_opt, defaultextension=".csv")
savename.write(key, ':', value)

因此,我更新了我的代码,尝试使用str(total_count.items()):转换为dict,因为在阅读json和pickle库后,我不太了解它们,它们似乎很复杂,因为我需要的是一个简单的文件输出,用户可以去查看。

我现在收到这个错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:UsersLewis CollinsAppDataLocalProgramsPythonPython35-32libtkinter__init__.py", line 1550, in __call__
return self.func(*args)
File "C:/Users/Lewis Collins/PycharmProjects/program_05.0.17/Home.py", line 108, in run_language_model
main.flag_detection()
File "C:UsersLewis CollinsPycharmProjectsprogram_05.0.17main_codemain.py", line 169, in flag_detection
for key, value in str(total_count.items()):
ValueError: not enough values to unpack (expected 2, got 1)

欢迎任何建议或反馈,提前感谢。

第一个问题是这行:

savename = asksaveasfile(file_opt, defaultextension=".csv")

这根本不是调用asksaveasfile的方法。asksaveasfile不将字典作为其第一个参数。如果你想使用file_opt1:中的选项,你应该这样称呼它

savename = asksaveasfile(defaultextension=".csv", **file_opt)

当你解决这个问题时,下一个问题是你试图在哪里写这句话:

savename.write(key, ':', value)

您将收到以下错误消息:TypeError: write() takes exactly 1 argument (3 given)。它的意思正是它所说的:你需要提供一个单独的论点,而不是三个论点。你可以通过给write恰好一个参数来解决这个问题:

savename.write("%s: %s" % (key, value))

但是,如果您只想将字典保存到一个文件中,json模块会使这变得非常容易,而不必迭代值。

要保存为json,请将flag_detection方法更改为如下所示:

import json
...
def flag_detection():
total_count = Counter(traffic_light)
EWT = tkinter.messagebox.askquestion('File Level', 'Would you like to save')
file_opt = options = {}
options['filetypes'] = [('all files', '.*'), ('text files', '.json')]
options['initialfile'] = 'myfile.json'
if EWT == 'yes':
savefile = asksaveasfile(defaultextension=".json", **file_opt)
json.dump(total_count, savefile)

如果您想保存为csv文件,请阅读DictWriter类的文档,该类以类似的方式工作。

最新更新