How To Delete Unsaved Tkinker Label?
I made this program where I am putting labels on a grid without saving them in a variable. I do this because then I can for loop through a list of classes and get the data from eac
Solution 1:
You can ask grid to give a list of widgets that it manages. You could then iterate over that list to find out which widget is in each row and column.
For example, if you wanted to be able to modify the text in the widget at a specific row or column, you could do something like this:
def set_item_text(master, row, column, text):
for child in master.grid_slaves():
grid_info = child.grid_info()
if grid_info['row'] == row and grid_info['column'] == column:
child.configure(text=text)
Here's an example that will change the text in row 2 column 2 to "hello, world":
import Tkinter as tk
def set_item_text(master, row, column, text):
for child in master.grid_slaves():
grid_info = child.grid_info()
if grid_info['row'] == row and grid_info['column'] == column:
child.configure(text=text)
root = tk.Tk()
for row in range(4):
for col in range(5):
tk.Label(
root, text="row %s col %s" % (row, col)
).grid(row=row, column=col, padx=8)
set_item_text(root, 2,2, "hello, world")
root.mainloop()
You could just as easily delete the widget, though if you're just wanting to refresh a "table-like thing" it's more efficient just to change the data than to delete and recreate all of the widgets.
Solution 2:
from pprint import pprint
from tkinter import Tk, Label
root = Tk()
Label(root, text='MyLabel').pack()
Label(root, text='MyLabel').pack()
Label(root, text='MyLabel').pack()
# as you did not kept references to the labels
# you have to look into the childrens of root
pprint(root.children) # show root children names
print()
root.children['!label2'].destroy() # do what you asked on the second Label
pprint(root.children) # check that it's gone
Post a Comment for "How To Delete Unsaved Tkinker Label?"