[英]Call function on resizing of window in Python Tkinter
我希望根据框架的宽度更改小部件在框架中的放置位置。 我有一个 function 可以执行此操作,但我希望它在帧大小发生变化时运行。 现在,如果我按下一个按钮,小部件会重新组织,但我当然正在寻找这个 function 在调整框架大小时运行,而不是在按下按钮时运行。
此示例中的框架被粘在其父 window 上并填充它,因此检测 window 调整大小或调整框架大小将是运行 function 的可接受触发器。
我已经使用智能感知寻找事件并在互联网上进行了一段时间的搜索,但还没有找到解决方案。
这是我的代码:
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()
感谢 TheLizzard 的建议,我根据您的建议找到了答案。 这是最终的代码,效果很好。 我将阅读有关绑定的更多信息以了解更多信息。 我使用"root.bind("<Configure>", reorganizeButtons)"
将该事件绑定到我试图运行的 function。 我还删除了按钮命令,因此它们不会导致小部件的重组。 这是包含解决方案的最终代码。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.