Home > other >  Inserting values from a list the tkinter text widget using commas
Inserting values from a list the tkinter text widget using commas

Time:06-07

I have created a UI that allows to check if the font used in the paragraphs of a Word document is Times New Roman or not. If paragraphs are written using any other font(s), the font name(s) are displayed to the user, via the tkinter (8.6) text widget. The invalid font(s) are stored in a set.

Each invalid font is separated by a comma in the text widget. However, a comma also appears after the last element of the set. This behaviour is not desired.

I would like to know how I can prevent a comma from appearing after the last element.

The code was written using Python (3.10) on PyCharm (Community Edition 2021.3.3).

The code is shown below. The code only shows the function used to check the font and not the whole code as it involves buttons and may be too long. Any help is welcomed.

# function that checks font
def font_name():
    if var1.get() == 1:
        # access file
        doc = Document(filename)
        # check font for paragraphs
        font = set()  # store all font names
        invalid_fonts = set()  # store unacceptable font
        VALID_FONT = 'Times New Roman'  # state the valid font
        for paragraphs in doc.paragraphs:
            if 'Normal' == paragraphs.style.name:
                for run in paragraphs.runs:
                    # add fonts from each run
                    font.add(run.font.name)
                    # check if fonts are valid
                    if run.font.name != VALID_FONT:
                        invalid_fonts.add(run.font.name)

        # check if all elements in font are VALID_FONT
        if {VALID_FONT} == font:
            output_display.insert("All paragraphs are written in Times New Roman font."   '\n')
            # check if all elements in font are not VALID_FONT
        elif {VALID_FONT} != font:
            output_display.insert('end', "Paragraph written in unrecognised font(s): ")
            for invalid_fonts in invalid_fonts:
                output_display.insert('end', invalid_fonts   ', ')  # add invalid font(s) to text widget

CodePudding user response:

You can use str.join() function:

import tkinter as tk

root = tk.Tk()


my_list = ['1', '2', '3', '3']

display = tk.Text(root)
display.insert(tk.END, ','.join(my_list))
display.pack()

root.mainloop()
  • Related