简体   繁体   中英

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. 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. 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. Strictly speaking you don't need the "left" tag, but it makes the intent of your code a bit clearer.

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")
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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