检测小部件何时从可见变为不可见或相反

Detect when a widget change from visible to invisible or the opposite

当我们可见的小部件变得不可见 .pack_forget() 或不可见的小部件变得可见时 .pack() 是否可以得到通知?

类似于button.bind("<Visible>", func_triggered_when_the_button_become_visible)

我想隐藏和显示整个框架,当我隐藏其中的小部件时,我希望重置它们的值。

根据 acw1668 的建议,我认为 <Map> 是您要找的。下面是一个例子,让你更好地理解:

from tkinter import *
from tkinter import messagebox

root = Tk()

def check(event): #function to be triggered only when the button is visible
    messagebox.showinfo('Visible','Seeing this message only because button is visible')

b = Button(root,text='Im going to disappear') #making button but not packing it(invisible)

b1 = Button(root,text='Click me to make the button disappear',width=50,command=lambda: b.pack_forget()) #to hide the button(to make invisible)
b1.pack(padx=10)

b2 = Button(root,text='Click me to make the button appear',width=50,command=lambda: b.pack()) #to show the button(to make visible)
b2.pack(padx=10)

b.bind('<Map>',check) #every time button is visible, check() is triggered

root.mainloop()

我发表评论是为了更好地理解这一点,如果有任何疑问,请告诉我。

文档中关于 <Map> 的更多信息:

The Map and Unmap events are generated whenever the mapping state of a window changes.

Windows are created in the unmapped state. Top-level windows become mapped when they transition to the normal state, and are unmapped in the withdrawn and iconic states. Other windows become mapped when they are placed under control of a geometry manager (for example pack or grid).

A window is viewable only if it and all of its ancestors are mapped. Note that geometry managers typically do not map their children until they have been mapped themselves, and unmap all children when they become unmapped; hence in Tk Map and Unmap events indicate whether or not a window is viewable.