2

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()
Max2603
  • 403
  • 1
  • 6
  • 23
  • You want to have the number on the left and the 'g' on the right, am I right? But I don't think it is possible to justify two parts of the same line differently. – j_4321 Oct 06 '17 at 09:17
  • yes that is what I want, to bad thats not possible... – Max2603 Oct 06 '17 at 09:36
  • I think you will have to use 2 text widgets, one for the numbers and one for the text. – j_4321 Oct 06 '17 at 09:42
  • I can't seem to find a way to have them justify differently on the same line. You could feasibly do some maths and calculate how many spacing characters you'd need to insert in between to separate the two strings but that's rather contrived and sloppy. – Ethan Field Oct 06 '17 at 09:49
  • @j_4321: yes, it's possible. – Bryan Oakley Oct 06 '17 at 12:18
  • 1
    @EthanField: the text widget supports right-justified tabstops, like many word processors. – Bryan Oakley Oct 06 '17 at 12:18
  • 1
    @BryanOakley Ladies and gents, this is why he has the gold badge. The thought hadn't crossed my mind, nice one! – Ethan Field Oct 06 '17 at 12:34

1 Answers1

7

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

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685