【问题标题】:Have PanedWindow separators "snap" to certain positions, instead of just allowing the user to choose any random position让 PanedWindow 分隔符“捕捉”到某些位置,而不是只允许用户选择任何随机位置
【发布时间】:2021-08-31 14:53:14
【问题描述】:

我有一个包含一些小部件的 tkinter PanedWindow,我希望用户能够将每个分隔符拖到某个位置,当他们松开鼠标按钮时,分隔符应该“捕捉”到列表中最近的位置我给程序的位置/比例。例如,假设我有一个包含两个按钮的 PanedWindow,并且我希望用户能够调整按钮的大小,使它们的比例可以是 1/4:3/4、1/2:1/2 或 3 /4:1/4 不仅仅是用户选择的任何宽度。有没有办法我可以做到这一点? 带有两个按钮的 PanedWindow 代码:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.geometry("400x400")

pw = tk.PanedWindow(root)
buttons = [ttk.Button(text=message) for message in ["goose", "duck"]]
for button in buttons:
    pw.add(button)
pw.pack(expand=True, fill="both")

root.mainloop()

有没有办法指定分隔符可以对齐的比例?

允许的职位:

调整大小时,按钮应对齐到这些位置中最近的位置。

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

    您可以通过将<ButtonRelease-1> 绑定到一个计算最近点的函数来做到这一点。然后,您可以使用此信息并使用 PanedWindow.sash_place(index, x, y) 更新窗扇位置。

    这是一个最小的例子:

    import tkinter as tk
    from tkinter import ttk
    
    
    def snap(event):
        width = pw.winfo_width()
        closest = min([width//2, width//4, width*3//4], key=lambda w: abs(w - event.x))
        pw.sash_place(0, closest, 1)
    
    
    root = tk.Tk()
    root.title("snappy")
    
    pw = tk.PanedWindow(root)
    buttons = [ttk.Button(text=message) for message in ["goose", "duck"]]
    
    for button in buttons:
        pw.add(button)
    pw.pack(expand=True, fill="both")
    
    pw.bind("<ButtonRelease-1>", snap)
    
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多