在tkinter文本小部件中左右对齐字符串

Max*_*603 2 textbox tkinter python-3.x text-justify

是否可以在每行的两侧textwidget中证明两个不同的字符串?我尝试了以下但它没有像预期的那样工作.

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()
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 5

您可以使用右对齐的tabstop逐行进行此操作,就像您可以在文字处理器中执行此操作一样.

诀窍是,只要窗口改变大小,就需要重置tabstop.您可以使用<Configure>在窗口大小更改时调用的绑定来执行此操作.

例:

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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述