无法获得像在Tkinter文本小部件中显示的文本来解释空格字符

问题描述

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':'我要\ n \ n显示的带有空格\ n \ n行字符的文本'}

要在“文本”小部件区域中显示如下:

“带空格的文本

我想要的行字符

显示

解决方法

这意味着您的文本文件中有文字“ \ n”。使用“ \ n”表示换行符只能在源代码中使用。但是python确实包含一个将其转换的函数:ast.literal_eval

from ast import literal_eval
# ...
converted_info_from_file_to_dictionary[key] = literal_eval(value)

这是一个骇客……如果您将数据保存为.json这样的格式,这将为您完成所有转换,而不是自己重新发明,那就更好了。