【问题标题】:Tkinter - How to resize frame containing a text widget (in all directions)?Tkinter - 如何调整包含文本小部件的框架(在所有方向上)?
【发布时间】:2023-02-26 04:31:46
【问题描述】:

我正在尝试调整某些分层 tkinter 组件的大小,主要是因为我很好奇。现在,似乎陷入了尝试调整包含文本小部件的框架的大小。这是我的尝试:

import tkinter as tk

def make_draggable(widget):
    widget.bind("<Button-1>", on_drag_start)
    widget.bind("<B1-Motion>", on_drag_motion)
    widget.bind("<Button-3>", on_resize_start)
    widget.bind("<B3-Motion>", on_resize_motion)

def on_drag_start(event):
    widget = event.widget
    widget._drag_start_x = event.x
    widget._drag_start_y = event.y

def on_drag_motion(event):
    widget = event.widget
    x = widget.winfo_x() - widget._drag_start_x + event.x
    y = widget.winfo_y() - widget._drag_start_y + event.y
    widget.place(x=x, y=y)

def on_resize_start(event):
    widget = event.widget
    widget._resize_start_x = event.x
    widget._resize_start_y = event.y
    widget._resize_width = widget.winfo_width()
    widget._resize_height = widget.winfo_height()

def on_resize_motion(event):
    widget = event.widget
    width = widget._resize_width + event.x - widget._resize_start_x
    height = widget._resize_height + event.y - widget._resize_start_y
    widget.place(width=width, height=height)
    widget.winfo_children()[0].configure(width=width, height=height)

main = tk.Tk()

frame = tk.Frame(main, bd=4, bg="grey")
frame.place(x=10, y=10)
make_draggable(frame)

notes = tk.Text(frame)
notes.pack()

main.mainloop()

它基于this 其他关于 SO 的回答。

这有效,但仅当在框架的底部和右侧(灰色部分)右键单击并拖动鼠标时。 我不知道如何让它在其他方向上工作(例如:顶部和左侧,如果可能的话,还有边缘)

如何在所有方向上做到这一点?

注意:我在 Win10 上使用 3.8.10 和 Tk 版本 8.6.9(补丁级别)

【问题讨论】:

    标签: python tkinter resize tkinter-text


    【解决方案1】:

    当您从顶部或左侧调整大小时,您也应该更改位置。此外,调整大小是相反的。如果从左向右拖动,宽度会变小,x 会增加。所以首先你需要检查你拖动的是哪个边框。

    def on_resize_motion(event):
        widget = event.widget
        if widget._resize_start_x < 4:
            x = widget.winfo_x() - widget._resize_start_x + event.x
            width = widget.winfo_width() - (event.x - widget._resize_start_x)    
        else:
            x = widget.winfo_x()
            width = widget._resize_width + event.x - widget._resize_start_x    
    

    如果您从左边界开始,这会减去鼠标位置的差异。其他部分与您所拥有的相同。你必须对 y 位置做同样的事情。

    最后,您需要更新 x 和 y 以及大小。

        widget.place(x=x, y=y, width=width, height=height)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多