在 tkinter 中获取文本小部件的内容大小

Get contents size of text widget in tkinter

有没有办法获取 Tk.Text 小部件内容的尺寸。例如,使用 canvas 我可以 canvas.bbox('all') 来给我内容的尺寸。这对我的程序至关重要,那么文本小部件怎么可能呢?

我希望能够在滚动条的内容不足时禁用滚动条。

import tkinter as tk

def getDims():
   print('How do I print the dimensions of the text box here')

root=tk.Tk()

text=tk.Text(root)
text.pack(fill='both')

var='How can I find the dimensions of this text inside the tkinter textbox widget in pixels ?'
text.insert('end',var)

b=tk.Button(root,text='Get Dimensions!',command=getDims)

您可以使用count 方法获取第一个字符和最后一个字符之间的像素数。此方法采用两个索引,然后是一个或多个表示您要计算的内容的字符串:chars、displaychars、displayindices、displaylines、indices、lines、xpixels 或 ypixels。 return 值是一个包含每个请求项目的计数的元组。

例如,要计算从第一个字符顶部到最后一个字符底部的像素数,您可以这样做:

ypixels = text.count("1.0", "end", "ypixels")[0]

另一种确定是否应显示滚动条的方法是调用 yview 方法。如果它 returns (0.0, 1.0),则表示整个文本都可见。如果任何部分滚出屏幕,该函数将 return 有所不同。