python-3.xtkintertextboxtext-justify

Justifying strings left and right in tkinter text widget


Is it possible to justify two diffrent strings in a textwidget on both sides in each line? I tried the following but it is not working like expected.

from tkinter import *

root = Tk()

t = Text(root, height=27, width=30)
t.tag_configure("right", justify='right')
t.tag_configure("left", justify='left')
for i in range(100):
    t.insert("1.0", i)
    t.tag_add("left", "1.0", "end")
    t.insert("1.0", "g\n")
    t.tag_add("right", "1.0", "end")
t.pack(side="left", fill="y")

root.mainloop()

Solution

  • You can do this on a line-by-line basis using a right-justified tabstop, just like you might do it in a word processor.

    The trick is that you need the tabstop to be reset whenever the window changes size. You can do this with a binding on <Configure> which is called whenever the window size changes.

    Example:

    import tkinter as tk
    
    def reset_tabstop(event):
        event.widget.configure(tabs=(event.width-8, "right"))
    
    root = tk.Tk()
    text = tk.Text(root, height=8)
    text.pack(side="top", fill="both", expand=True)
    text.insert("end", "this is left\tthis is right\n")
    text.insert("end", "this is another left-justified string\tthis is another on the right\n")
    
    text.bind("<Configure>", reset_tabstop)
    root.mainloop()
    

    enter image description here