在 tkinter 文本小部件中左右对齐字符串
Justifying strings left and right in tkinter text widget
是否可以在每一行的两侧对齐文本小部件中的两个不同字符串?我尝试了以下方法,但它没有像预期的那样工作。
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()
您可以使用右对齐制表位逐行执行此操作,就像您在文字处理器中执行此操作一样。
诀窍是只要 window 改变大小,您就需要重置制表位。您可以通过 <Configure>
上的绑定来执行此操作,只要 window 大小发生变化,就会调用该绑定。
示例:
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()
是否可以在每一行的两侧对齐文本小部件中的两个不同字符串?我尝试了以下方法,但它没有像预期的那样工作。
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()
您可以使用右对齐制表位逐行执行此操作,就像您在文字处理器中执行此操作一样。
诀窍是只要 window 改变大小,您就需要重置制表位。您可以通过 <Configure>
上的绑定来执行此操作,只要 window 大小发生变化,就会调用该绑定。
示例:
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()