在不知道标签的情况下从 tkinter 中的网格正方形中删除所有标签

Deleting all Labels from grid square in tkinter without knowing Labels in first place

所以我想要一些类似于这段代码看起来应该做的事情,但是 'grid()' 没有定义:

for label in grid(column = 1, row = 2):
    label.forget()

w.grid_slaves(row=None, column=None)

Returns a list of the widgets managed by widget w.

If no arguments are provided, you will get a list of all the managed widgets. Use the row= argument to select only the widgets in one row, or the column= argument to select only the widgets in one column.

参考finding widgets on a grid (tkinter module)

import tkinter as tk
root = tk.Tk()

# Show grid_slaves() in action
def printOnClick(r, c):
    widget = root.grid_slaves(row=r, column=c)[0]
    print(widget, widget['text'])

# Make some array of buttons
for r in range(5):
    for c in range(5):
        btn = tk.Button(root, text='{} {}'.format(r, c),
                        command=lambda r=r, c=c: printOnClick(r, c))
        btn.grid(row=r, column=c)

tk.mainloop()

即使已经给出了一个适当的例子,如果你想遍历所有元素而不指定确切的 row/column:

,我想用 winfo_children() 给出另一个例子
from tkinter import Tk, Label, Button


def my_func():
    # get all children of root
    my_children = root.winfo_children()

    # iterate over children
    for wdg in my_children:
        # print widget information
        print(f"Widget: {type(wdg)},"
              f" Row: {wdg.grid_info()['row']}, Column: {wdg.grid_info()['column']},"
              f" Text: {wdg['text']}")
        # modify text of all labels
        if isinstance(wdg, Label):
            wdg.config(text=wdg["text"] + ".")


root = Tk()
Button(root, text="Click", command=my_func).grid(row=0, column=0, columnspan=3)

for i in range(1, 4):
    for j in range(3):
        Label(root, text=f"Row {i} Col {j}").grid(row=i, column=j)

root.mainloop()