LoginSignup
1
1

More than 1 year has passed since last update.

tkinterで作ったLabelの右端の座標【Python】

Last updated at Posted at 2020-03-27

tkinterで作ったLabelの右端の座標が知りたい。

Frame,Labelの配置方法など基礎的な部分は【tkinter】Labelを使ってみるなどを参照してください。

(本記事はtkinterでLabelを動かす【Python】の一部です。検索しやすいように別記事に分けてみました。)

問題


txt=Labeltext
label=ttk.Label(master=root,text=txt,font=("メイリオ",fontsize))
label.place(x=xx,y=yy)

としたとき、labelの左端はもちもんxxである。
では、そのLabelの表示の上での右端の座標は?

答え

label.winfo_reqwidth()+xx

解説(オマケ)

私ははじめlen(txt)*fontsize(fontsizeの単位はピクセルpx)でいけると思った。しかし、tkinterでLabelを動かす【Python】で紹介した右端にきたら折り返すプログラムにて、文字列によってはLabelが右端に行く前に折り返してしまった。
missrei.gif

これは、len(txt)としていることに起因する。この実装の場合、
iiiii
AAAAA
が同じ長さ扱いにされてしまうからである。

そこで登場するのが__winfo_reqwidth()__である。
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.

要するに、指定されたオブジェクト(ここではLabel)をFrame上で表示するのに最小限必要なサイズを返してくれる。これにlabelの左端の座標xxを足せば、現在のlabelの右端の座標を取得できる。
seikourei.gif
うまく右端判定ができた。

ちなみに、`winfo_reqheight()`で高さが取得できる。すなわち、

label=ttk.Label(master=root,text=txt,font=("メイリオ",fontsize),foreground="red",background="green")
print(label.winfo_reqwidth())
>>125
print(label.winfo_reqheight())
>>45
txt="Labeltext\nLabeltext"#二行に渡って表示する場合
label=ttk.Label(master=root,text=txt,font=("メイリオ",fontsize),foreground="red",background="green")
print(label.winfo_reqwidth())
>>125#横幅は変わらない
print(label.winfo_reqheight())
>>86#2行になったので増えた。ただし、≠45*2である点に注意
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1