Problem with tkinter text insert wordstart

Viewed 152

I tried to get the current word in a tkinter text widget. Here’s my code:

import tkinter as tk

win = tk.Tk()

text = tk.Text(win)
text.insert('end', 'a b abc')
text.pack(fill='both', expand=1)
def get_word():
    global text
    print(repr(text.get('insert -1c wordstart', 'insert wordend')))

tk.Button(win, text='Get Word', command=get_word).pack()

win.mainloop()

When:

  • The cursor is at the end of ‘a’ or ‘b’:
    Returns ‘a ‘ or ‘b ‘
  • The cursor is at the end of ‘abc’:
    Returns ‘abc\n’
  • The cursor is in the word ‘abc’:
    Returns ‘abc’

I want to get the word right before the cursor, like when the cursor is after ‘b’, I want it to return ‘b’; return ‘abc’ when the cursor is after ‘abc’.

So how can I do this? Thanks for any ideas!

2 Answers

I hope this answer is what you want since you didn't clear out what exactly you want. Remove the -1c in index_1 parameter to solve the extra space added to word retrieved and extra newlines.

import tkinter as tk

win = tk.Tk()

text = tk.Text(win)
text.insert('end', 'a b abc')
text.pack(fill='both', expand=1)
def get_word():
    global text
    print(repr(text.get('insert wordstart', 'insert wordend')))

tk.Button(win, text='Get Word', command=get_word).pack()

win.mainloop()

this way if cursor is after a a single space is returned and if before a an a is returned with no extra spaces. also no new lines are appended to abc.

Try this:

import tkinter as tk

win = tk.Tk()

text = tk.Text(win)
text.insert("end", "a b abc")
text.pack()

def get_word(event=None):
    word = text.get("insert wordstart", "insert wordend")
    if word in " \n":
        word = text.get("insert -1c wordstart", "insert -1c wordend")
    print(repr(word))

text.bind("<ButtonRelease-1>", get_word)
# If you want to test it using the arrow keys:
text.bind("<KeyRelease-Left>", get_word)
text.bind("<KeyRelease-Right>", get_word)

win.mainloop()

I just combined your solution with @Khaled's solution. It first checks if @Khaled's solution works. If it doesn't, it checks your solution.

Related