Python tkinter,如何从光标位于 ScrolledText 框中的按钮输入文本?

Python tkinter, how to enter text from a button where my cursor is located in a ScrolledText box?

以下代码创建了一个 ScrolledText 框,用户可以在其中键入内容。他们还可以选择其中一个按钮来输入西班牙语字符。

from    functools import partial
import  tkinter as tk
from    tkinter import scrolledtext

root = tk.Tk()
root.title("Test")
root.geometry('950x700')
root.configure(background='ivory3')

frame_button=tk.Frame(root, background='ivory3')
frame_button.grid(row=0,column=0, pady=2)

def insert_char(char):
    """When the user presses one of the spanish language character buttons
       put the correct character in the textw box. """
    try:
       my_focus = str(root.focus_get())
       if char == "á": 
          textw.insert("end","á")
       elif char == "é": 
            textw.insert("end","é")
    except Exception as ex:
       txt = "ERROR: insert_char(): " + str(ex)
       clear_txt()
       textw.insert(tk.END, txt)    # Write the error text onto the screen
       return(-1)

# GUI Box that the user can either type or paste text to be read into.
textw = scrolledtext.ScrolledText(root,width=90,height=21)
textw.grid(row=1, column=0)
textw.config(background="light grey", foreground="black",
                 font="Times 14 bold", wrap='word', relief="sunken", bd=5)
textw.delete('1.0', tk.END)  # Delete any old text on the screen
textw.update()               # Clear the screen.

Button_AA=tk.Button(frame_button,width=4,bg="grey",fg="white",text="á",
                    font="Times 12 bold", relief=tk.RAISED, bd=10,
                    command=partial(insert_char, "á"))

Button_AE=tk.Button(frame_button,width=4,bg="grey",fg="white",text="é",
                    font="Times 12 bold", relief=tk.RAISED, bd=10,
                    command=partial(insert_char, "é"))

Button_AA.grid(row=0,column=0)
Button_AE.grid(row=0,column=1)

root.mainloop()

假设用户输入 'Hable con ella.',他们意识到它应该是 'Hablé con ella.' 如果他们在 e 之后点击并按下退格键,我希望他们能够点击 é 按钮来修复这个单词。问题是 é 会放在句末,给我 'Habl con ella.é'

如何让我的按钮将字符放在光标所在的位置?

textw.insert(tk.INSERT,"á")

ScrolledText 是一种文本小部件,因此如果您对此有任何疑问,可以查看 tkinter.Text 的命令。

您明确将文本添加到末尾。如果要在插入光标处插入,请使用索引“insert”而不是“end”。

textw.insert("insert","á")