Python Tkinter line in font differs compared to text widgit as line grows
A text object containing a string (in the specified font) seems to give inconsistent results depending on the length of the string. For example:
from Tkinter import *
import tkFont
root=Tk()
t_Font = tkFont.Font(family='Helvetica', size=12, weight='bold')
t_text='New.'
t_frame = Frame(root, bd=0, height=10, width=t_Font.measure(t_text))
t = Text(master=t_frame, height=1, width=len(t_text), bd=1, font=t_Font, padx=0 )
print '\n\nMeasured:',t_Font.measure(t_text),'Frame req:',t_frame.winfo_reqwidth(),'As Text:',t.winfo_reqwidth()
Measured: 38 Frame req: 38 As text: 38
t_text='New title.' t_frame = Frame(root, bd=0, height=10, width=t_Font.measure(t_text)) t = Text(master=t_frame, height=1, width=len(t_text), bd=1, font=t_Font, padx=0 ) print '\n\nMeasured:',t_Font.measure(t_text),'Frame req:',t_frame.winfo_reqwidth(),'As Text:',t.winfo_reqwidth()
Measured: 69 Frame req: 69 As Text: 92
The extra 6 characters increased the size and size of the frame by 31 pixels, but the Text object increased by 54.
What is it because of?
source to share
I understand that it was 7 months, but I wanted to answer this to everyone who happened to be here, like me.
Short answer: if you were using a fixed-width font then that would be a match (eg "Courier New"). But Helvetica is a proportional font, so its characters don't have the same width.
Font.measure () and Frame.winfo_reqwidth () use the actual size for these lines of text in that font / weight / size because their width is in pixels.
A text widget, on the other hand, has the width specified in characters.
So it takes the number of characters each time and tries to guess, for that font / weight / size, how big to make the widget handle them, but not the exact characters you are using. It uses the null character, "0", as its average character size.
If you change your second set t_text, t_frame, t to t_text2, t_frame2, t2 and then pack () and run root.mainloop (), you can play around with the 2 widgets you created. The first with "New". the dialed does not even show ".". because the created field is a little too small and the second widget shows "New Title". with extra spaces to the left. Now if you delete them and enter "0000" for the first widget and "0000000000" for the second, you will see that the widgets are filled in exactly.
I found this by reading the Tcl / Tk docs for text-width at https://www.tcl.tk/man/tcl8.6/TkCmd/text.htm#M21
source to share