我创建了一个聊天应用程序,其中我使用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()
您可以将
Listbox
替换为Text
小部件,该小部件在“禁用”模式下自动包装长行。每次插入文本时,您只需将小部件恢复为“正常”模式:顺便说一句,
Listbox
和Text
小部件都支持索引'end',因此您不必跟踪插入了多少行。在相关问题 更多 >
编程相关推荐