tkinter - 无法获得像 Tkinter Text 小部件中显示的文本来解释空格字符
问题描述
def search():
converted_info_from_file_to_dictionary = {}
with open('file.txt') as working_file:
for line in working_file:
key, value = line.strip().split("|--|")
converted_info_from_file_to_dictionary[key] = (value)
print(converted_info_from_file_to_dictionary)
entered = textentry.get()
output.delete("1.0", END)
try:
to_be_updated = converted_info_from_file_to_dictionary[entered]
except:
to_be_updated = "Sorry no Info \n available !!!\n"
output.insert("1.0", to_be_updated)
信息保存在字典行中 {'any text': 'text with space \n\n line characters which I want \n\n to show'}
希望在文本小部件区域中显示如下:
"带空格的文本
我想要的行字符
以显示”
解决方案
这意味着您的文本文件中有文字“\n”。使用“\n”表示换行符只应该在源代码中工作。但是 python 确实包含一个函数来转换它:ast.literal_eval
.
from ast import literal_eval
# ...
converted_info_from_file_to_dictionary[key] = literal_eval(value)
这是一个技巧……如果您将数据保存为像 .json 这样的格式会更好,它会为您完成所有这些转换,而不是自己重新发明它。
推荐阅读
- python - 如何在另一个字典中提取 Python 字典并返回他的一些键
- javascript - response.getselectedbutton() 不是函数?
- mongodb - Mongodb 多字段相等性检查
- electron - Electron - 防止窗口从渲染过程中关闭
- angular - 如何从 ngx-extended-pdf-viewer 的 node_modules 中省略子文件夹
- c# - 如果触地则团结跳跃
- azure - 发布 URL https://waws-prod-am2-xxx.publish.azurewebsites.windows.net/ 无法访问
- python - torch.cat 沿负维度
- python - 创建新模型对象时出现 IntegrityError
- bazel - 解析 Bazel 构建事件协议以搜索构建失败的目标和错误消息的最佳方法是什么?