Search code examples
tkinterstrip

How to remove curly braces from a text widget


I would like to list the list of frame.conifg in the Text Widget. The characters "{}" should be removed from the text. Can someone explain to me, why that will not removed with the following code?

liste  = frame_01.config()

for item in liste:
       texteditor.insert(tk.INSERT, (item.strip("{}"), ":", liste[item], "\n"))

This is how the list looks like: enter image description here

With this code I get the following error message: texteditor.insert(tk.INSERT, (item.translate(str.maketrans('', '', '{}')), ":", self.mainwindow.liste[item], "\n")) TypeError: list indices must be integers or slices, not str

for item in liste:
           texteditor.insert(tk.INSERT, (item.translate(str.maketrans('', '', '{}')), ":", liste[item], "\n"))

Solution

  • The curly braces aren't in the data, they are only added by tkinter because you are passing a list to a function that expects a string. Tcl (the embedded language that tkinter uses) encodes lists differently than python, by adding curly braces around list elements that have spaces or tabs.

    The solution is to explicitly format the data rather than trying to let Tcl format the data. One way is to do it something like this:

    for item in liste:
    
        # convert the list of values to a list of strings
        values = [str(x) for x in liste[item]]
    
        # explicitly join the list of strings to create a single string
        str_values = " ".join(values)
    
        # insert the string into the text widget
        textedit.insert("end", f"{item}: {str_values}\n")