在 Python Tkinter 中调用调整窗口大小的函数

gar*_*t73 4 python events layout resize tkinter

我希望根据框架的宽度更改小部件在框架中的放置位置。我有一个函数可以执行此操作,但我希望它在帧大小发生变化时运行。现在,如果我按下按钮,小部件会重新组织,但当然我正在寻找此函数在调整框架大小时运行,而不是在按下按钮时运行。

此示例中的框架粘在其父窗口上并填充它,因此检测窗口大小调整或框架大小调整将是运行该函数的可接受的触发器。

我已经使用智能感知查找事件,也在互联网上进行了一段时间的搜索,但还没有找到解决方案。

这是我的代码:

from tkinter import *

def reorganizeButtons():
    # if the widths of the buttons exceed width of frame, stack vertically
    # else stack horizontally
    if button1.winfo_width()+button2.winfo_width()>frame.winfo_width():
        button1.grid(row=0,column=0, sticky=NSEW)
        button2.grid(row=1,column=0,sticky=NSEW)
    else:
        button1.grid(row=0,column=0,sticky=NSEW)
        button2.grid(row=0,column=1,sticky=NSEW)
    frame.update_idletasks()
    print ()
    print ("button1 width: ", button1.winfo_width())
    print ("button2 width: ", button2.winfo_width())
    print ("frame width: ", frame.winfo_width())

def main():
    global root
    global frame
    global button1
    global button2
    root = Tk()
    root.maxsize(400,200) # sets a limit on how big the frame can be
    root.title("Enlarge Window, then Press a Button")

    frame=Frame(root)
    frame.grid(row=0, column=0, sticky=NSEW)
    root.columnconfigure(0,weight=1)
    root.rowconfigure(0,weight=1)

    button1=Button(frame, text="---Button1---", command=reorganizeButtons)
    button2=Button(frame, text="---Button2---", command=reorganizeButtons)

    reorganizeButtons()

    root.mainloop()

main()
Run Code Online (Sandbox Code Playgroud)

gar*_*t73 6

感谢TheLizzard的建议,我根据你的建议找到了答案。这是最终的代码,效果很好。我将阅读更多有关绑定的内容以了解更多信息。我曾经"root.bind("<Configure>", reorganizeButtons)"将该事件绑定到我试图运行的函数。我还删除了按钮命令,这样它们就不会导致小部件的重组。这是包含解决方案的最终代码。

from tkinter import *

def reorganizeButtons(event):
    # if the widths of the buttons exceed width of frame, stack vertically
    # else stack horizontally
    if button1.winfo_width()+button2.winfo_width()>frame.winfo_width():
        button1.grid(row=0,column=0, sticky=NSEW)
        button2.grid(row=1,column=0,sticky=NSEW)
    else:
        button1.grid(row=0,column=0,sticky=NSEW)
        button2.grid(row=0,column=1,sticky=NSEW)
    frame.update_idletasks()
    print ()
    print ("button1 width: ", button1.winfo_width())
    print ("button2 width: ", button2.winfo_width())
    print ("frame width: ", frame.winfo_width())

def main():
    global root
    global frame
    global button1
    global button2
    root = Tk()
    root.maxsize(200,200) # sets a limit on how big the frame can be
    root.title("Resize to Reorganize Buttons")

    frame=Frame(root)
    frame.grid(row=0, column=0, sticky=NSEW)
    root.columnconfigure(0,weight=1)
    root.rowconfigure(0,weight=1)

    button1=Button(frame, text="---Button1---")
    button2=Button(frame, text="---Button2---")

    root.bind("<Configure>", reorganizeButtons)

    root.mainloop()

main()
Run Code Online (Sandbox Code Playgroud)