1
votes

I am trying to create a roguelike using the Text widget.

I have figured out a few things, namely that I can set the size of the widget using width and height options and that I can find the pixel height or width of said widget. However, what I want to do is have the widget resizable (pack(expand="yes", fill="both")) but be able to refresh the displayed text on a resize. Is there a way to get the character dimensions when the widget is running without resorting to winfo_width() and math based on pixel dimensions of characters?

3
You could pack the text widget in a frame and get the size of the frame... - mgilson
That just gives you the pixel size. - jaccarmac
Sorry, I didn't read your post carefully enough. I thought you wanted the pixel size. My fault. - mgilson
"refresh the displayed text on a resize" why do you want to do that? - Honest Abe
So that the player can resize his game. - jaccarmac

3 Answers

2
votes

I've run into that exact same problem a couple times jaccarmac, and to my knowledge there is no way to find the width of a string of characters. Really the only way is to use the winfo_ commands: width, height, geometry. However, it kind of sounds like you just want to make sure that all of the text is displayed if you change the label and add more text. If that is the case, you don't have to worry about it. That should all be taken care of by the widgets themselves. If you don't see them expanding to show all of your label, that usually means one of the widgets containing that label is not set to expand (either using expand=YES with .pack, or columnconfigure(i, weight=1) for .grid).

A final thought; in the pack arguments make sure it's YES, and not "yes". That uppercase YES is not a string, but a variable name defined by Tkinter.

0
votes

There is no way to automatically get the width in characters, but it's easy to calculate, assuming you're using a fixed width font. One way to do this is to use the font_measure method of a font object. Use font_measure to get the width of a '0' (or any other character for that matter; I think tk users zero internally, not that it matters with a fixed width font), then use this in your calculations.

0
votes

This is an old question, but after doing some research I've found that there actually is a way to get height/width info directly without maths or playing with font widths using the Text widget's cget() method:

text_widget = tk.Text()
width_in_char = text_widget.cget('width')
height_in_char = text_wdiget.cget('height')

Since the Text widget stores its height and width configuration in characters, simply querying for those parameters will give you what you're looking for.