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!