我正在编写一个小程序,其目的是在窗口大小更改时运行调整大小方法。为此,我使用了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()
Run Code Online (Sandbox Code Playgroud)
输出:
widget .!toplevel
height 200 width 200
widget .!toplevel.!scrollbar …Run Code Online (Sandbox Code Playgroud)