0

我有以下代码,我想用鼠标扩展文本小部件。(垂直双箭头)。但这似乎很不对劲。当我开始编写代码时,窗口扩展到无穷大(实际上可能不是很长)。如果我删除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, column=0, sticky=tk.NSEW)

    text = tk.Text(main_frame, cursor="sb_v_double_arrow")
    text.grid(row=LABEL_COUNT, column=0, 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()

图形用户界面

我的做法对吗?我该如何解决这个问题?

4

0 回答 0