简体   繁体   English

在文本Tkinter中对齐行

[英]Justify line in text Tkinter

I'm trying to build a Bot who's responding to the user question, I would like to display the user question on the right side of the Frame and the Bot answer to the left side. 我正在尝试建立一个负责回答用户问题的Bot,我想在框架的右侧显示用户问题,在Bot的左侧显示答案。 I've read a post about justify in text with the tag ( How to set justification on Tkinter Text box ) but I can't apply that on my code, and I'm not familiar with the tags at all. 我已经阅读了有关带有标签的文本中对齐的文章( 如何在Tkinter文本框中设置对齐 ),但是我无法将其应用到代码中,而且我对标签一点也不熟悉。 Can you please help me, what am I doing wrong ? 您能帮我吗,我做错了什么? (If this isn't clear please tell me) (如果不清楚,请告诉我)

Here is my code : 这是我的代码:

from tkinter import *

window = Tk()

ia_answers= "test\n"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)

ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)

text = Text(ia_frame, state='disabled', text="ok")
text.pack()
text.tag_configure("right", justify='right')
text.tag_add("right", 1.0, "end")
def Enter_pressed(event):
    """Took the current string in the Entry field."""
    input_get = input_field.get()
    input_user.set("")
    text.configure(state='normal')
    text.insert('end', input_get)
    text.insert('end',ia_answers)
    text.configure(state='disabled')

input_field.bind("<Return>", Enter_pressed)
window.mainloop()

Create two tags -- "left" and "right", set the alignment property, and then apply the tag to the text when you insert it. 创建两个标签-“ left”和“ right”,设置alignment属性,然后在插入文本时将其应用于文本。 Strictly speaking you don't need the "left" tag, but it makes the intent of your code a bit clearer. 严格来说,您不需要“ left”标签,但是它使您的代码意图更加清晰。

text = Text(ia_frame, state='disabled', text="ok")

text.tag_configure("right", justify="right")
text.tag_configure("left", justify="left")
...
text.insert("end", "this is right-justified\n", "right")
text.insert("end", "this is left-justified\n", "left")
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM