如何在tkinter python中动态添加多行文本?

2024-10-17 08:25:02 发布

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

我创建了一个聊天应用程序,其中我使用ListBox显示聊天历史记录。它看起来很好,直到我进入一个长的刺超过屏幕。有没有一种方法可以中断字符串并在新行中显示,或者其他任何方式来显示完整的字符串。我是新来的Tkinter和我不知道有许多小部件可用。在

这是我的示例代码

from tkinter import *

class Actions:
    def chatUpdate(chat):
        chatlist.insert(Actions.chatLast,chat)
        Actions.chatLast=Actions.chatLast+1
        chatlist.pack( side=LEFT, fill=BOTH)
        chatBox.config(command=chatlist.yview)


def callUpdater():
    txt=textBox.get()
    text_text.set("")
    Actions.chatUpdate(txt)


root = Tk()
root.title("Chat App")
frame1 = Frame(root, bd=4)
frame1.pack(side=TOP)

frame2 = Frame(root, bd=4)
frame2.pack(side=TOP)

frame3 = Frame(root, bd=4)
frame3.pack(side=TOP)

# chat box
chatBox = Scrollbar(frame1)
chatBox.pack(side=RIGHT, fill=Y)
chatlist = Listbox(frame1, yscrollcommand = chatBox.set, width=50)
Actions.chatLast=0
Actions.chatUpdate("                        ")

# text box
textView = Label(frame2, text="Input: ")
textView.pack(side=LEFT)
text_text = StringVar()
textBox = Entry(frame2, textvariable=text_text, bd=0, width=40, bg="pink")
textBox.pack(side=RIGHT)

# send button
button = Button(frame3, text="Send", fg="black", command=callUpdater)
button.pack(side=TOP)
root.mainloop()

Tags: textactionstopchatrootsidebdpack
1条回答
网友
1楼 · 发布于 2024-10-17 08:25:02

您可以将Listbox替换为Text小部件,该小部件在“禁用”模式下自动包装长行。每次插入文本时,您只需将小部件恢复为“正常”模式:

from tkinter import *

def callUpdater():
    text = textBox.get()
    textBox.delete(0, 'end')
    chat.configure(state='normal')
    chat.insert('end', text + '\n')
    chat.configure(state='disabled')

root = Tk()
chatBox = Scrollbar(root)
chat = Text(root, wrap='word', state='disabled', width=50,
            yscrollcommand=chatBox.set)
chatBox.configure(command=chat.yview)

chat.grid(row=0, columnspan=2, sticky='ewns')
chatBox.grid(row=0, column=2, sticky='ns')
Label(root, text="Input: ").grid(row=1, column=0)

textBox = Entry(root, bd=0, width=40, bg="pink")
textBox.grid(row=1, column=1)

Button(root, text="Send", command=callUpdater).grid(row=2, columnspan=2)
root.mainloop()

顺便说一句,ListboxText小部件都支持索引'end',因此您不必跟踪插入了多少行。在

相关问题 更多 >