首页 > 解决方案 > 如何在 tkinter 的文本小部件中将文本输入到换行符?

问题描述

我正在创建一个简单的程序,在 tkinter 的列表框中显示文本。有时我想显示的文本比列表框大,所以它会离开屏幕。我想知道是否有办法让文本在下面开始一个新行而不是离开屏幕。

代码

from tkinter import *

root = Tk()

text = Text(root, width = 50, height=15, bg="#2C2F33", fg="white",wrap=WORD)
text.grid(row=0, column=0, padx=10)

while True:
    message = input("Enter a message: ")
    text.insert(INSERT, message)

root.mainloop()

问题:

消息未在换行符上输入

预期结果

预期结果

非常感谢所有帮助!

标签: python-3.xtkinterlistbox

解决方案


Listbox 小部件是一个可供选择的项目菜单。列表框项目不可能分布在多行或多行中。

您应该使用另一个名为 Text 的小部件

from tkinter import *

root = Tk()
message = "This message is too long to display on the listbox. I hope that someone will help me find a solution to this problem."
text = Text(root, width = 50, height=15, bg="#2C2F33", fg="white",wrap=WORD)

text.insert(INSERT, message)

text.grid(row=0, column=0, padx=10)

root.mainloop()

注意:
wrap:此选项控制过宽行的显示。设置 wrap=WORD 它将在最后一个适合的单词之后换行。使用默认行为 wrap=CHAR 时,任何过长的行都会在任何字符处中断。

在此处输入图像描述


推荐阅读