📜  Python| Tkinter 中的 forget_pack() 和 forget_grid() 方法

📅  最后修改于: 2022-05-13 01:55:44.156000             🧑  作者: Mango

Python| Tkinter 中的 forget_pack() 和 forget_grid() 方法

如果我们想从屏幕或顶层取消映射任何小部件,则使用forget()方法。有两种忘记方法forget_pack() (类似于forget() )和forget_grid()分别与pack()grid()方法一起使用。

forget_pack()方法——

Syntax: widget.forget_pack()

widget can be any valid widget which is visible.
代码#1:
# Imports tkinter and ttk module
from tkinter import * 
from tkinter.ttk import *
  
# toplevel window
root = Tk()
  
# method to make widget invisible
# or remove from toplevel
def forget(widget):
  
    # This will remove the widget from toplevel
    # basically widget do not get deleted
    # it just becomes invisible and loses its position
    # and can be retrieve
    widget.forget()
  
# method to make widget visible
def retrieve(widget):
    widget.pack(fill = BOTH, expand = True)
  
# Button widgets
b1 = Button(root, text = "Btn 1")
b1.pack(fill = BOTH, expand = True)
  
# See, in command forget() method is passed
b2 = Button(root, text = "Btn 2", command = lambda : forget(b1))
b2.pack(fill = BOTH, expand = True)
  
# In command retrieve() method is passed
b3 = Button(root, text = "Btn 3", command = lambda : retrieve(b1))
b3.pack(fill = BOTH, expand = True)
  
# infinite loop, interrupted by keyboard or mouse
mainloop()

输出:
忘记包()方法

忘记之后
忘记之后

检索后
检索后

注意按钮 1 在忘记之前和之后以及检索之后的位置差异。

forget_grid()方法 -

Syntax: widget.forget_grid()

widget can be any valid widget which is visible.

注意:此方法只能与grid()几何方法一起使用。

代码#2:

# Imports tkinter and ttk module
from tkinter import *
from tkinter.ttk import *
  
# toplevel window
root = Tk()
  
# method to make widget invisible
# or remove from toplevel
def forget(widget):
  
    # This will remove the widget from toplevel
    # basically widget do not get deleted
    # it just becomes invisible and loses its position
    # and can be retrieve
    widget.grid_forget()
  
# method to make widget visible
def retrieve(widget):
    widget.grid(row = 0, column = 0, ipady = 10, pady = 10, padx = 5)
  
# Button widgets
b1 = Button(root, text = "Btn 1")
b1.grid(row = 0, column = 0, ipady = 10, pady = 10, padx = 5)
  
# See, in command forget() method is passed
b2 = Button(root, text = "Btn 2", command = lambda : forget(b1))
b2.grid(row = 0, column = 1, ipady = 10, pady = 10, padx = 5)
  
# In command retrieve() method is passed
b3 = Button(root, text = "Btn 3", command = lambda : retrieve(b1))
b3.grid(row = 0, column = 2, ipady = 10, pady = 10, padx = 5)
  
# infinite loop, interrupted by keyboard or mouse
mainloop()

输出:
忘记网格()方法

忘记之后
忘记之后

检索后
检索后

请注意,按钮 1 的位置在忘记检索后保持不变。使用grid_forget()方法,您可以在检索后将其放置在任何网格上,但通常会选择原始网格。