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()
Hello everyone, I have a long paragraph, I split it using '\n' and use it in canvas. I don't want to do the same thing in every paragraph, it's hard. Is there a way for me to automatically insert the '\n' in certain parts of the paragraph?
I will have too many paragraphs
CodePudding user response:
use the textwrap
module. For the example I unwrapped the paragraph by removing newlines, but you wouldn't do that in cases where text was wrapped manually.
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()
CodePudding user response:
If "certain parts" means a number of words or some lenght, you can write a function do add \n for you based on that.