0

这是解释我的问题的代码:

from tkinter import *
import csv

root= Tk()
root.geometry("1080x720")
TextA, TextB = '',''

ListA = [["Unimportant Title"],["This is a sentence","\n I start the first line of the next line","\nHelp me"], ["sublist", "number 2"]]
for element in ListA[1]:
    TextA = TextA + element

ListB = []
with open ('demo.csv', 'r', newline="\n") as t:
    r = csv.reader(t, delimiter='|')
    for lines in r:
        ListB.append(lines)
    t.close
print(ListB)
for element in ListB[1]:
    TextB = TextB + element

label1 = Label(root, font=("Calibri", 14), text=TextA, fg="white", bg="#282828")
label1.place(relx=0.4,rely=0.3)
label2 = Label(root, font=("Calibri", 14), text=TextB, fg="white", bg="#282828")
label2.place(relx=0.4,rely=0.5)

root.mainloop()

这是以下内容demo.csv

"Unimportant Title"
"This is a sentence"|"\n I start the first line of the next line"|"\nHelp me"
"sublist"|"number 2"

我面临的问题是,当标签显示时TextA\n被识别为换行符,我得到这样的输出,这正是我想要的:

This is a sentence
I start the first line of the next line
Help me

但是当显示TextB从 csv 文件中读取的标签时,\n无法识别并且我没有得到我想要的输出。相反,我得到它是这样的:

This is a sentence\n I start the first line of the next line\nHelp me

我应该怎么办?

我已经尝试删除和保留它,newline="\n"但它没有工作......

我知道这看起来很具体,但这是我正在处理的代码的重要部分。到目前为止,我还没有找到解决方案,或者更确切地说在哪里应用该解决方案。

4

1 回答 1

0

如果您查看以下输出print(ListB)

[['Unimportant Title'], ['This is a sentence', '\\n I start the first line of the next line', '\\nHelp me'], ['sublist', 'number 2']]

你会发现\n在文件中被读取为\\n. 您需要将其转换回\n

for element in ListB[1]:
    TextB += element.replace('\\n', '\n')
于 2022-01-10T04:28:30.683 回答