Text
ウィジェットに\n
個の文字(複数行)を含むカスタム文字列を保持しています。Tkinter.text - 動的文字列の高さを計算するには?
ウィジェットは、panedwindow
の中に配置され、panedwindow
のサッシュを調整して、Text
ウィジェット内の文字列全体を表示します。
文字列は本質的に動的です(つまり、アプリケーションの他のメソッドによって更新されています)。
Text
ウィジェットがwrap='word'
で設定されているため、どのようにして文字列の高さをピクセル単位で計算して、それに応じてサッシを調整できますか?
文字列がウィジェットに読み込まれた後、text.dlineInfo('end -1c')[1] + text.dlineinfo('end -1c')[3]
(行のy座標+高さ)を使用しようとしました。問題は、最後の行が表示されていない場合、dlineinfoはnone
を返します。
また、Font.measure
ルーチンを使用しようとしましたが、これにはText
ウィジェットのラップ機能は含まれていません。ここで
は、最小完全、かつ検証可能な例である:
import tkinter
from tkinter import scrolledtext
class GUI():
def __init__(self, master):
self.master = master
self.body_frame = tkinter.PanedWindow(self.master, orient='vertical', sashwidth=4)
self.body_frame.pack(expand=1, fill='both')
self.canvas_frame = tkinter.Frame(self.body_frame)
self.description_frame = tkinter.Frame(self.body_frame)
self.body_frame.add(self.canvas_frame, sticky='nsew')
self.body_frame.add(self.description_frame, sticky='nsew')
tkinter.Button(self.canvas_frame, text='Update Text', command = lambda : self.update_text("""
A very long string with new lines
A very long string with new lines
A very long string with new lines
A very long string with new lines
A very long string with new lines
A very long string with new lines
""")).pack(fill='x')
self.field_description = scrolledtext.ScrolledText(self.description_frame, width=20, wrap='word')
self.field_description.pack(expand=1, fill='both')
self.master.update()
self.body_frame.sash_place(0,0,self.body_frame.winfo_height() - 50) # force sash to be lower
def update_text(self, description):
self.field_description.delete('1.0', 'end')
self.field_description.insert('1.0', description)
height = self.body_frame.winfo_height()
lastline_index = self.field_description.index('end - 1c')
text_height = self.field_description.dlineinfo(lastline_index)[1] + \
self.field_description.dlineinfo(lastline_index)[3]
self.body_frame.sash_place(0, 0, height - text_height)
root = tkinter.Tk()
my_gui = GUI(root)
root.mainloop()
'end -1c'を' end'に変更すると助けになりますか?私は '-1c'が終了カウントから最後の行を取り除くと信じています。 –
@SierraMountainTech:いいえ。問題は、最後の行が表示されていない場合、dlineinfoはNoneを返すことです。 – NirMH
ああ。私は何がわかるのか分かります。これが[最小限で完全で検証可能な例](https://stackoverflow.com/help/mcve)として設定されていると便利です。 –