【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()方法, 检索后可以将其放置在任何网格上, 但是通常会选择原始网格。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
推荐阅读
- Python使用OpenCV对图像进行灰度缩放
- Python Tkinter中的geometry方法用法示例
- Python Tkinter中的grid()方法用法示例
- Python groupby方法删除所有连续的重复项
- #导入Word文档图片# Linux下Shell脚本语言编程
- #导入Word文档图片# Linux下automake工具使用(自动构建Makefile文件)
- 使用uni-app开发非原生小程序微信/支付宝小程序
- 小程序开发快速上手快速入门篇
- 全流程分析Netty设计思路与实践