如何打印长字符串列表中的50个单词

2024-03-28 19:14:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在tkinter窗口中显示字符串列表中的文本。但问题是字符串非常长,我希望它在一行中只显示50个字符,然后在下一行中剩余50个字符,以此类推为完整字符串。你知道吗

news_full=['Finance Minister Arun Jaitley said on Friday that the rules for small businesses and exporters would be eased under the Goods and Services Tax (GST), a move that could provide relief to thousands of small firms.', 'Employers may now have more leeway to withhold birth control coverage on religious grounds, according to new rules issued by the US Department of Health and Human Services.', "Samantha Ruth Prabhu and Naga Chaitanya tied the knot on Friday evening. And we need to thank Naga's father and actor Nagarjuna Akkineni for sharing the first pictures of the couple. Here are the latest photos from Samantha Ruth Prabhu and Naga Chaitanya's grand Goa wedding. Scroll on.", 'The storm brought heavy rain to Central America, where more than 20 people died. The storm is headed toward Louisiana, where Gov. John Bel Edwards said, "I\'m not going to tell you I am not concerned."', "A police official said investigators don't think anyone else was in the shooter's room before the Las Vegas attack, but are looking if anyone knew about his plans.", "MELBOURNE, Australia (AP) — Australia cricket captain Steve Smith will return home from the team's tour of India with a right shoulder injury, Cricket Australia said Saturday.", 'Hurricane Nate gained force as it headed toward the central Gulf of Mexico early Saturday after drenching Central America in rain that was blamed for 21 deaths.', 'India, meanwhile, said there were “no new developments” at the face-off site, and that the status quo continues.', 'The possible sale of the advanced system can go ahead if congress does not object within 30 days.', 'Thousands of people gather at 40 locations across the country on Saturday as part of the Stop Adani Alliance']

root=Tk()

for s in news_full:
    texr2=Label(root,text=s,font=("sans-serif",32))
    texr2.pack()

root.geometry('545x800')

root.mainloop()

so expected output is (ex for first element of list]

Finance Minister Arun Jaitley said on Friday that 
the rules for small businesses and exporters would
be eased under the Goods and Services Tax (GST), 
a move that could provide relief to thousands of 
small firms.

列表的所有元素都相同。你知道吗


Tags: andoftheto字符串forthaton
2条回答

如果可能的话,当然可以使用TK的自动包装。但如果没有,您可以执行以下操作:

from textwrap import wrap

s = "Some very long string. Or short. It does not matter really. Blah, blah, blah!\nIt can be multilined too!"
print "\n".join(wrap(s, 25))

所以这将把任何文本包装成每行25个字符。将返回行列表。你知道吗

创建Label对象时可以使用wraplength使文本自动换行。你知道吗

这是以屏幕单位给出的,因此如果窗口是545像素宽(如示例中所示),则可以传递545的wraplength值,以便它在窗口中进行包装。你知道吗

要使文本与预期输出中的文本左对齐,可以传递参数justify=LEFTanchor=W。你知道吗

因此,创建标签的行将如下所示:

texr2=Label(root, text=s, wraplength=545, anchor=W, justify=LEFT, font=("sans-serif",14))

请注意,我更改了字体大小,因此所有文本都适合窗口大小。你知道吗

您还希望通过使用参数fill=BOTHexpand=True来确保所有内容都正确填充:

texr2.pack(expand=True, fill=BOTH)

相关问题 更多 >