我正在编写一个小程序,意图是在窗口大小调整时运行一个调整大小的方法。为此,我使用了toplevel.bind("<Configure>", self.resize)
。虽然这确实可以进行调整大小,但该方法会在许多情况下被调用:滚动时、使用某些按钮时,即使窗口大小并没有因这些操作之一而改变。如何绑定事件,以便它仅在更改窗口大小时被调用?
import tkinter as tk
def resize(event):
print("widget", event.widget)
print("height", event.height, "width", event.width)
parent = tk.Toplevel()
canvas = tk.Canvas(parent)
scroll_y = tk.Scrollbar(parent, orient="vertical", command=canvas.yview)
scroll_x = tk.Scrollbar(parent, orient="horizontal", command=canvas.xview)
frame = tk.Frame(canvas)
# put the frame in the canvas
canvas.create_window(0, 0, anchor='nw', window=frame)
# make sure everything is displayed before configuring the scrollregion
canvas.update_idletasks()
canvas.configure(scrollregion=canvas.bbox('all'),
yscrollcommand=scroll_y.set,
xscrollcommand=scroll_x.set)
scroll_y.pack(fill='y', side='right')
scroll_x.pack(fill='x', side='bottom')
canvas.pack(fill='both', expand=True, side='left')
parent.bind("<Configure>", resize)
parent.mainloop()
输出:
widget .!toplevel
height 200 width 200
widget .!toplevel.!scrollbar
height 286 width 17
widget .!toplevel.!scrollbar2
height 17 width 382
widget .!toplevel.!canvas
height 269 width 382
widget .!toplevel
height 286 width 399
widget .!toplevel
height 286 width 399
widget .!toplevel.!can
即使窗口只有一个画布和滚动条,调整大小事件在用户交互之前被调用了7次。我该如何停止这种疯狂的行为,并在窗口真正调整大小时才调用调整大小函数?