-1

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • You have to show us what all have you tried. Do you have a minimal-reproducible example to include in your question? – Billy Apr 30 '22 at 19:32
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Apr 30 '22 at 20:24
  • 1
    Do you want to add the parenthesis as the user types, or at some time in the future? Have you worked through a tkinter tutorial that teaches about bindings? – Bryan Oakley Apr 30 '22 at 23:09

1 Answers1

0

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()
Billy
  • 1,157
  • 1
  • 9
  • 18