'How to remove a phrase from text widget? Using tkinter, python
If I press the button it inserts a phrase in a textbox widget. When I press the button again I would like to remove the inserted phrase from the textbox. But I can't figure out how to do that.
...
premade_buttons_frame = tk.Frame(main_frame)
premade_buttons_frame.pack()
self.b1 = tkm.Button(premade_buttons_frame, text="Button text", padx=5, command=self.premade_phrase_b1)
self.b1.grid(row=0, column=0)
...
def premade_phrase_b1(self):
premade_phrase = "My phrase. "
button_text = "Button text"
#it the phrase already is inserted
if self.b1.cget("text") == 'Used':
#get all the text from the textbox
textbox_text = self.symptom_textbox.get("1.0",'end-1c')
#find the start index of the phrase
start_index_of_string = textbox_text.find(premade_phrase)
print("index_of_string", start_index_of_string)
#try to delete the phrase
self.symptom_textbox.delete(f"1.{start_index_of_string}", f"1.{len(premade_phrase)}")
# set button text back to original text
self.b1.configure(text=button_text)
#insert the phrase in the textbox at the end
elif self.b1.cget("text") == button_text:
self.symptom_textbox.insert(tk.END, premade_phrase)
#change button text to Used
self.b1.configure(text="Used")
If I only add the phrase it works. But If I type anything else in the textbox before trying to delete the phrase the delete will be messed and not deleting the added phrase (only parts of it).
How can I delete the inserted phrase (when pressing the button again after inserted the phrase)?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
