I extended Tk.Label class in order to customize my needs, and for some odd reason is not destroying the object, even after calling the widget.destroy()
, when I am updating values. So basically, I would end up with the self.update
old value on bottom and new value on top of old value.
import tkinter as tk
class GUI(tk.Frame):
def __init__(self, master, *args, **kwargs)
tk.Frame.__init__(self, *args, **kwargs)
self.master = master
self.update = Label(self.master, "Select a value", 0, 0)
btn = tk.Button(text="Select", command=self.update_btn)
btn.grid(row=0, column=1)
def update_btn(self):
# Destroy method being called here
self.update.destroy()
self.update = Label(self.master, "New value", 0, 0)
class Label(tk.Label):
def __init__(self, root, label_name, row, col, *args, **kwargs):
tk.Label.__init__(self, *args, **kwargs)
label = tk.Label(root, text=label_name, *args, **kwargs)
label.grid(row=row, column=col)
Any help would be much appreciated.
Your class is weird. You create Label
inside Label
and you shows only inner label. And later you destroy outer label but it will not destroy inner label.
Correct version is
class Label(tk.Label):
def __init__(self, root, label_name, row, col, *args, **kwargs):
tk.Label.__init__(self, *args, master=root, text=label_name, **kwargs)
self.grid(row=row, column=col)
In Python 3.x you can write it
class Label(tk.Label):
def __init__(self, root, label_name, row, col, *args, **kwargs):
super().__init__(*args, master=root, text=label_name, **kwargs)
self.grid(row=row, column=col)
Now to update text you can use
self.update["text"] = "..."
or
self.update.config(text="...")
instead of `self.update.label["text"] = ...
EDIT: class GUI
is also weird. You creat Frame
but you don't show it (you don't use pack/grid) and you use main window as parent for Label
. For Button
you don't even set parent so you may get weird result in some situations.
import tkinter as tk
class GUI(tk.Frame):
def __init__(self, master, *args, **kwargs):
super().__init__(*args, master=master, **kwargs)
# show frame
self.pack()
# add to frame (self)
self.update = Label(self, "Select a value", 0, 0)
# add to frame (self)
btn = tk.Button(self, text="Select", command=self.update_btn)
btn.grid(row=0, column=1)
def update_btn(self):
self.update['text'] = "New value"
#self.update.config(text="New value")
class Label(tk.Label):
def __init__(self, root, label_name, row, col, *args, **kwargs):
super().__init__(*args, master=root, text=label_name, **kwargs)
self.grid(row=row, column=col)
root = tk.Tk()
GUI(root)
root.mainloop()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.