So i would like something along the lines of what this code looks like it should do but 'grid()' isn't defined:
for label in grid(column = 1, row = 2):
label.forget()
CodePudding user response:
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.
Refer 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()
CodePudding user response:
Even though a proper example was given already, i want to give another example with winfo_children()
if you want to iterate over all elements without specifying the exact row/column:
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()