使用 python tkinter 库时如何调整选项卡大小?

Dyl*_*ham 2 python tkinter python-3.x

我正在尝试使用 python 中的 tkinter 库构建一个文本编辑器应用程序。默认制表符大小约为 15 个空格。如何将此选项卡大小调整为 4 个空格左右?

fhd*_*sdg 5

您可以使用Text小部件的tabs选项来控制制表位的位置。用于定义宽度的选项是(从此处复制)

<none>
  The number specifies a distance in pixels.
c
  The number specifies a distance in centimeters on the screen.
i
  The number specifies a distance in inches on the screen.
m
  The number specifies a distance in millimeters on the screen.
p
  The number specifies a distance in printer's points (1/72 inch) on the screen.
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这些都不包含大量字符/空格。您可以选择您喜欢的一些像素,但如果您希望它尽可能接近四个空格,tkinter 有一种方法来“测量”特定字符串的宽度,如本答案所示。使用它,您可以执行以下操作:

from tkinter import *
import tkinter.font as tkfont

root = Tk()

text = Text(root)
text.pack()

font = tkfont.Font(font=text['font'])
tab = font.measure('    ')

text.config(tabs=tab)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)