I want to know the coordinates of the right end of Label made with tkinter.
Please refer to [tkinter] Try using Label etc. for the basic part such as how to arrange Frame and Label.
(This article is a part of Running Label with tkinter [Python]. I have divided it into separate articles for easy search.)
txt=Labeltext
label=ttk.Label(master=root,text=txt,font=("Meiryo",fontsize))
label.place(x=xx,y=yy)
Then, the left end of label
is Mochimon xx.
Then, what are the coordinates of the right end of the Label display?
label.winfo_reqwidth()+xx
At first I thought that len (txt) * fontsize
(fontsize
is in pixels px) could be used. However, with the program introduced in Running Label with tkinter [Python], it wraps before the Label goes to the right end, depending on the character string. I have.
This is due to the fact that it is len (txt)
. For this implementation
iiiii
AAAAA
Is treated as the same length.
That's where __winfo_reqwidth ()
__ comes in.
According to https://effbot.org/tkinterbook/widget.htm
Returns the “natural” width for this widget. The natural size is the minimal size needed to display the widget’s contents, including padding, borders, etc. This size is calculated by the widget itself, based on the given options. The actual widget size is then determined by the widget’s geometry manager, based on this value, the size of the widget’s master, and the options given to the geometry manager.
In short, it returns the minimum size required to display the specified object (Label in this case) on the Frame. By adding the leftmost coordinate xx of label
to this, you can get the rightmost coordinate of the current label
.
I was able to judge the right end successfully.
label=ttk.Label(master=root,text=txt,font=("Meiryo",fontsize),foreground="red",background="green")
print(label.winfo_reqwidth())
>>125
print(label.winfo_reqheight())
>>45
txt="Labeltext\nLabeltext"#When displaying over two lines
label=ttk.Label(master=root,text=txt,font=("Meiryo",fontsize),foreground="red",background="green")
print(label.winfo_reqwidth())
>>125#The width does not change
print(label.winfo_reqheight())
>>86#Since it became two lines, it increased. However, ≠ 45*Note that it is 2.
Recommended Posts