问题描述
我有以下代码,我想用鼠标展开文本小部件。 (垂直双箭头)。但似乎有些不对劲。当我开始编写代码时,窗口扩展到无穷大(实际上可能不是,但很长)。如果我删除 on_resize
它可以工作,但文本会扩展到底部。我想向上扩展它。
import tkinter as tk
import tkinter.font as tkfont
LABEL_COUNT = 8
LABELS_MIN_HEIGHT = 100
def main():
root = tk.Tk()
root.rowconfigure(0,weight=1)
root.columnconfigure(0,weight=1)
main_frame = tk.Frame(root)
main_frame.grid(row=0,column=0,sticky=tk.NSEW)
main_frame.rowconfigure(tuple(range(LABEL_COUNT+1)),weight=1)
main_frame.columnconfigure(0,weight=1)
for label_id in range(LABEL_COUNT):
tk.Label(main_frame,text=f"Test label{label_id}").grid(row=label_id,sticky=tk.NSEW)
text = tk.Text(main_frame,cursor="sb_v_double_arrow")
text.grid(row=LABEL_COUNT,sticky=tk.NSEW)
text.bind('<Button1-Motion>',lambda event: on_motion(event,text))
main_frame.bind("<Configure>",lambda event: on_resize(event,text))
root.mainloop()
def on_resize(event: tk.Event,text: tk.Text):
"""update text widget size based on root"""
expected_height = event.height - LABELS_MIN_HEIGHT
set_text_height(text,expected_height)
def on_motion(event: tk.Event,text: tk.Text):
expected_height = text.winfo_height() - event.y
set_text_height(text,expected_height)
def set_text_height(text: tk.Text,expected_height: int):
"""set given height to the text widget"""
# Get how much space a line holds
line_height = tkfont.nametofont(text.cget("font")).metrics('linespace')
# Divide expected_height to the line_height to find out how many lines we need
text.config(height=(expected_height//line_height))
if __name__ == "__main__":
main()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)