Is there a way I can get the dimensions of the contents of a Tk.Text widget. For example with a canvas I can do canvas.bbox('all')
to give me the dimensions of the contents. This is crucial to my program so how is this possible with a text widget?
I want to be able to disable a scrollbar when there is not enough contents for the scrollbar to be active.
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)
You can use the count
method to get the number of pixels between the first and last characters. This method takes two indexes, and then one or more strings representing what you want to count: chars, displaychars, displayindices, displaylines, indices, lines, xpixels, or ypixels. The return value is a tuple containing the count of each requested item.
For example, to count the pixels from the top of the first character to the bottom of the last character you could do this:
ypixels = text.count("1.0", "end", "ypixels")[0]
Another way to determine if you should show the scrollbar is to call the yview
method. If it returns (0.0, 1.0)
, that tells you that the entire text is visible. If any portion is scrolled off of the screen, that function will return something different.