Python Tkinter中的forget_pack()和forget_grid()用法

【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()

输出如下:
Python Tkinter中的forget_pack()和forget_grid()用法

文章图片
忘记之后
Python Tkinter中的forget_pack()和forget_grid()用法

文章图片
检索后
Python Tkinter中的forget_pack()和forget_grid()用法

文章图片
注意忘记之前和之后以及检索之后, 按钮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()

输出如下:
Python Tkinter中的forget_pack()和forget_grid()用法

文章图片
忘记之后
Python Tkinter中的forget_pack()和forget_grid()用法

文章图片
检索后
Python Tkinter中的forget_pack()和forget_grid()用法

文章图片
注意按钮1的位置在之后保持不变忘记和恢复。用grid_forget()方法, 检索后可以将其放置在任何网格上, 但是通常会选择原始网格。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读