首页 > 解决方案 > 无法获得像 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'}

希望在文本小部件区域中显示如下:

"带空格的文本

我想要的行字符

以显示”

标签: tkintertextwidgetcharacterspace

解决方案


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

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

这是一个技巧……如果您将数据保存为像 .json 这样的格式会更好,它会为您完成所有这些转换,而不是自己重新发明它。


推荐阅读