如何不从 Tkinter 中的 ScrolledText 溢出文本?

问题描述

我只是在学习 Tkinter 和 Python。我正在尝试设计一个聊天机器人。在设计聊天机器人时,我写了一个现在满溢的回复。 显然,在这里它可以使用 '\n' 分解,但我将从 json 文件获取长响应,或者用户可以发送长查询。 那么,我该怎么做才能使文本保留在窗口中并且不会溢出?

欢迎任何进一步的建议。

这是我的 output

这是我的代码

from datetime import datetime
from tkinter import *
import tkinter
import tkinter.scrolledtext as ScrolledText


def send():
    ChatLog.tag_configure('tag-left',justify='left')
    ChatLog.tag_configure('tag-right',justify='right')
    ChatLog.config(state=norMAL)

    frame1 = Frame(ChatLog,bg="#d0ffff")
    Label(
        frame1,text="You: What you can do?",font=(
            "Arial",11),bg="#d0ffff").grid(
            row=0,column=0,sticky="w",padx=5,pady=5)
    Label(
        frame1,text=datetime.Now().strftime("%H:%M"),7),bg="#d0ffff").grid(
            row=1,sticky="e")

    frame2 = Frame(ChatLog,bg="#ffffd0")
    Label(
        frame2,text="Bot: I can guide you through Adverse drug reaction list,Blood pressure tracking,Hospitals and Pharmacies",bg="#ffffd0").grid(
            row=0,pady=5)
    Label(
        frame2,bg="#ffffd0").grid(
            row=1,sticky="e")

    ChatLog.insert('end','\n ')
    ChatLog.window_create('end',window=frame1)
    ChatLog.tag_add("tag-right","end-1c linestart","end-1c lineend")
    ChatLog.insert('end',window=frame2)
    ChatLog.config(state=disABLED)


base = Tk()
base.title("chatbot")
base.geometry("400x500")
base.resizable(width=FALSE,height=FALSE)
base.configure(bg='white')

ChatLog = ScrolledText.ScrolledText(
    base,bd=0,bg="white",height="8",width="50",font="Arial")
ChatLog.config(state=disABLED)

SendButton = Button(
    base,font=(
        "Verdana",12,'bold'),text="Send",width="8",height=5,bg="#fd94b4",activebackground="#ff467e",fg='#ffffff',command=send)

EntryBox = Text(base,width="29",height="5",font="Arial")


ChatLog.place(x=6,y=6,height=386,width=383)
EntryBox.place(x=6,y=401,height=90,width=265)
SendButton.place(x=275,height=90)

base.mainloop()

解决方法

虽然可以配置标签以使其自动换行,但这是极少数情况之一,Message 小部件可能更合适,因为它自动支持换行和对齐。

有关标签和消息小部件有何不同的详细信息,请参阅Message and Label Difference? (tkinter)

示例:

Message(
    frame2,text="Bot: I can guide you through Adverse drug reaction list,Blood pressure tracking,Hospitals and Pharmacies",font=(
        "Arial",11),bg="#ffffd0").grid(
        row=0,column=0,sticky="w",padx=5,pady=5)

screenshot

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...