tkinter: How to start a new line after opening parenthesis?

115 Views Asked by At

I have a program with my code, the idea is: I have a textbox, I put a text in it and with I button I need to create a new line after any open parenthesis. I have little experience with tkinter and I don't even know where to start to do this, I also went to do further research but found no documentation.

1

There are 1 best solutions below

1
On

Solution

  • Use the Text.search method to search for opening parentheses.
  • In order to find all matches, put it in a loop and adjust the startposition after every match.
  • In order to prevent adding multiple newlines on everytime you search, add a check
def add_newlines():
    startpos = "1.0"
    while True:
        pos = text.search("(", startpos, stopindex=tk.END)
        if not pos:
            break

        startpos = f"{pos}+1c"
        if text.get(startpos) != "\n":
            text.insert(startpos, "\n")

Example

import tkinter as tk


root = tk.Tk()

def add_newlines():
    startpos = "1.0"
    while True:
        pos = text.search("(", startpos, stopindex=tk.END)
        if not pos:
            break

        startpos = f"{pos}+1c"
        text.insert(startpos, "\n")

text = tk.Text(root)
text.pack(fill=tk.BOTH, expand=1)
text.insert(tk.END, "Hello(test)\n(test)((test))")

btn = tk.Button(root, text="Add Newlines", command=add_newlines)
btn.pack()

root.mainloop()