如何自动添加'\n'到段落

How to automatically add '\n' To paragraph

我有一个很长的段落,我用 '\n' 拆分它并在 canvas 中使用它。我不想在每个段落中都做同样的事情,因为我会有太多的段落。有没有办法让我在段落的某些部分自动插入 '\n'

from tkinter import *

w = Tk()

canvas = Canvas(width = 800, height = 800)
canvas.place(relx=0, rely=0)

paragraph = "Lorem ipsum dolor sit amet, consectetur\nadipiscing elit. Nam sollicitudin rhoncus\nipsum. Morbi sed metus sollicitudin, tristique\nsapien vitae, cursus nulla. Mauris vel accumsan\npurus. Vestibulum orci est, euismod non ultricies\nporttitor, blandit at mi. Integer ut lectus congue,\nfinibus magna a, mattis erat. Proin quis egestas\nligula."

canvas.create_text(50, 50, text=paragraph, anchor=NW, font="Times 5 bold")

w.mainloop()

使用textwrap模块。例如,我通过删除换行符展开段落,但在手动换行文本的情况下你不会这样做。

from tkinter import*
import textwrap

w=Tk()

canvas =Canvas(width = 800, height = 800)
canvas.place(relx=0,rely=0)

paragraph="Lorem ipsum dolor sit amet, consectetur\nadipiscing elit. Nam sollicitudin rhoncus\nipsum. Morbi sed metus sollicitudin, tristique\nsapien vitae, cursus nulla. Mauris vel accumsan\npurus. Vestibulum orci est, euismod non ultricies\nporttitor, blandit at mi. Integer ut lectus congue,\nfinibus magna a, mattis erat. Proin quis egestas\nligula."

# lazy way to get rid of the newlines for test
paragraph = paragraph.replace("\n", " ")
wrapped = textwrap.fill(paragraph, 40)

canvas.create_text(50,50,text=wrapped,anchor=NW,font="Times 5 bold")

w.mainloop()

如果“某些部分”是指一些单词或一些长度,您可以在此基础上编写一个函数来为您添加\n。