我有一個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),將會有所幫助。 –