pythontkinter

How to delete last word of Tkinter ScrolledText Widget


I have a scrolledtext.ScrolledText widget which has some text in it, what I want to do is delete the last word of the widget. I tried searching it up on the internet and found nothing.

If sample code is needed I can give it.

I have tried to find the index of the final word since I do know what it is, here is the code:

    from tkinter import *
    from tkinter import ttk, scrolledtext

    target_list = rndm_words

    words = scrolledtext.ScrolledText(root, font=("Arial", 15), width=40, height=2)
    words.insert(INSERT, " ".join(rndm_words))
    words.config(state=DISABLED)

    words.config(state=NORMAL)
    words.delete(words.index(target_list[-1]), END)
    words.config(state=DISABLED)

rndm_words is a random 50 words from the Oxford 3000


Solution

  • I've put together a quick example for you. The del_last_word function first collects all of the words in the text widget into a list via split, then clears the text and replaces it with everything but the last word. When you click the button at the bottom, the last word in the text field will disappear.

    import tkinter as tk
    from tkinter import ttk
    from tkinter.scrolledtext import ScrolledText
    
    
    def del_last_word() -> None:
        content = text.get('1.0', tk.END)
        words = content.split()
        try:
            new_words = words[:-1]  # all but the last word
        except IndexError:  # no more words
            return
        text.delete('1.0', tk.END)
        text.insert(tk.INSERT, new_words)
    
    
    root = tk.Tk()
    text = ScrolledText(root)
    text.pack(expand=True, fill='both')
    text.insert(tk.INSERT, 'Lorem ipsum dolor sit amet edipiscing elit. Suscipit facere maxime aut magnam ut. Debitis est nulla et aut sed quod odit. Ut consequatur delectus sed aperiam commodi. Sint ducimus voluptas labore est repudiandae. Magnam et error aut corporis qui consequatur aut modi. Autem et itaque repudiandae.')
    btn_delete = ttk.Button(root, text='Delete Last Word', command=del_last_word)
    btn_delete.pack()
    
    
    if __name__ == '__main__':
        root.mainloop()