gpt4 book ai didi

Python 3.5 Tkinter如何将字典保存到文件

转载 作者:行者123 更新时间:2023-12-01 03:24:41 26 4
gpt4 key购买 nike

所以我的问题是,我正在运行一个程序,一旦完成基本功能,就会出现一个弹出框,询问用户是否要保存文件,如果"is",则会出现一个保存对话框。因为我保存的数据是一个字典值,所以我从 tkinter 收到错误。我尝试使用“.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:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__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:\Users\Lewis Collins\PycharmProjects\program_06.01.17\main_code\main.py", line 179, in flag_detection
savename = asksaveasfile(file_opt, defaultextension=".csv")
File "C:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\filedialog.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:\Users\Lewis Collins\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__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:\Users\Lewis Collins\PycharmProjects\program_05.0.17\main_code\main.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")

这根本不是如何调用asksaveasfileasksaveasfile 不将字典作为其第一个参数。如果您想使用 file_opt1 中的选项,您应该这样调用它:

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

当你解决这个问题后,下一个问题是你尝试用这个语句编写的地方:

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

您收到此错误消息:TypeError:write() 仅接受 1 个参数(给定 3 个参数)。它的意思正是它所说的:您需要提供一个参数而不是三个参数。您可以通过给 write 恰好 1 个参数来解决这个问题:

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 上的文档。类以类似的方式工作。

关于Python 3.5 Tkinter如何将字典保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41503397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com