首页 > 解决方案 > 使用 map lambda 销毁小部件 tkinter

问题描述

我正在学习一些用于 python 的内置函数,我尝试使用 map 和 lambda 函数来破坏画布的子小部件,但它没有用。

这是我尝试过的:

from tkinter import *

root = Tk()

C = Canvas(root, bg='red',width=400,height=400)
C.pack()

Label(C,text='Label').pack()

Button(C,text='Button').pack()

map(lambda child: child.destroy(), C.winfo_children())

root.mainloop()

标签: pythontkinterlambda

解决方案


map返回一个iterable,传递给的函数map只会在iterable被消耗/迭代时应用于它的项目。

您可以在地图上使用any()//可迭代list()来消费其项目,以便应用该函数:tuple()

any(map(lambda child: child.destroy(), C.winfo_children()))

或者如果您想要单行的话,只需使用列表理解:

[child.destroy() for child in C.winfo_children()]

推荐阅读