Modifying a widget that was formerly embedded in a tkinter text widget produces an error

Viewed 62

I'm experimenting with re-using widgets that were once embedded in a tkinter text widget. In my code, I add 2 radiobuttons to the text widget. I then added a button that removes the 2nd radiobutton from the text widget. After its removal, I attempt to modify the text of the removed radiobutton. When I do, I get the following error:

line 1629, in _configure self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) _tkinter.TclError: invalid command name ".!frame.!text.rb2

I'm really puzzled why my code produces this error and what can be done to fix the problem. Here's my test code:

from tkinter import *

root = Tk()
frm = Frame()
frm.pack()

var = IntVar()

sb = Scrollbar(frm, orient=VERTICAL)
sb.pack(fill=Y, side=RIGHT, expand=FALSE )

text = Text(frm,  yscrollcommand=sb.set)
text.pack(expand=True, side=LEFT, fill=BOTH)
sb.config(command = text.yview)
rbparent=text
rb1 = Radiobutton(rbparent, name="rb1", text="Radio Button 1", value=1)
rb1.pack()
text.window_create(END, window=rb1)
text.insert(END,'\n')

rb2 = Radiobutton(rbparent, name="rb2", text="Radio Button 2", value=2)
rb2.pack()
text.window_create(END, window=rb2)
text.insert(END,'\n')

def onClick():
    print(text.window_names())
    text.delete('2.0',END)
    print(text.window_names())
    rb2.pack_forget()
    #The following statement produces the error
    rb2.config(text="Modified Radio Button 2")
    print(f"rb2.text:{rb2['text']}")
    print()
    print("onClick Finished...")

Button(frm, text="Click Me", command=onClick).pack()

root.mainloop()

In the for what it's worth department, I've experimented with not removing the embedded radiobutton from the text widget and the modification to the radiobutton's text attribute is successful. The problem only occurs when I remove the embedded radiobutton from the text widget.

Is there a way to modify the attributes of an embedded radiobutton widget after its been removed from a text widget?

1 Answers

I'm really puzzled why my code produces this error

It's because you're deleting the widget with this line of code:

text.delete('2.0',END)

This is what the canonical documentation says about calling delete: "If the range of text containing the embedded window is deleted then the window is destroyed."

If you want to remove the embedded widget from the text widget without destroying it, you can do it like this:

text.window_configure('2.0', window='')
Related