问题描述
我只是在学习 Tkinter 和 Python。我正在尝试设计一个聊天机器人。在设计聊天机器人时,我使用了 tag-right 配置,以便消息转移到右侧,而响应保留在左侧。但是消息部分没有移动,现在我该怎么做才能使消息部分向右移动?
这是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: Hello",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="w")
frame2 = Frame(ChatLog,bg="#ffffd0")
Label(
frame2,text="Bot: Hello",bg="#ffffd0").grid(
row=0,pady=5)
Label(
frame2,bg="#ffffd0").grid(
row=1,sticky="w")
ChatLog.insert('end','\n','tag-right')
ChatLog.window_create('end',window=frame1)
ChatLog.insert('end','\n ')
ChatLog.window_create('end',window=frame2)
ChatLog.config(state=disABLED)
base = Tk()
base.title("Chat Bot")
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()
解决方法
只需更改标签即可。您需要交换标签。
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: Hello",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="w")
frame2 = Frame(ChatLog,bg="#ffffd0")
Label(
frame2,text="Bot: Hello",bg="#ffffd0").grid(
row=0,sticky="e",pady=5)
Label(
frame2,bg="#ffffd0").grid(
row=1,column=1,sticky="e")
ChatLog.insert('end','\n','tag-left')
ChatLog.window_create('end',window=frame1)
ChatLog.insert('end','\n ','tag-right')
ChatLog.window_create('end',window=frame2)
ChatLog.config(state=DISABLED)
输出:
,您将“标签右侧”选项卡添加到带有标签的行之前的行中。您需要将标记应用于带有窗口的行。
这是一种方法:
ChatLog.window_create('end',window=frame2)
ChatLog.tag_add("tag-right","end-1c linestart","end-1c lineend")
由于您使用标签来呈现实际文本,因此您还需要确保标签中的文本右对齐,并且标签本身与框架的右侧对齐