hunminpark
hunminpark

Reputation: 214

get() method of Tkinter text widget - doesn't return the last character

I'm writing some GUI program in Tkinter. I'm trying to trace the contents of the Text widget by using Text.get() method.
I heard that I can get(1.0, 'end') to get current contents written on the widget, but it doesn't give the most recent character I typed.

This is a simple example I wrote:

import Tkinter as tk

class TestApp(tk.Text, object):
    def __init__(self, parent = None, *args, **kwargs):
        self.parent = parent
        super(TestApp, self).__init__(parent, *args, **kwargs)

        self.bind('<Key>', self.print_contents)

    def print_contents(self, key):
        contents = self.get(1.0, 'end')
        print '[%s]' % contents.replace('\n', '\\n')

if __name__ == '__main__':
    root = tk.Tk()
    app = TestApp(root, width = 20, height = 5)
    app.pack()
    root.mainloop()

If I type 'abcd', it prints 'abc\n', not 'abcd\n'. ('\n' is automatically added after the last line by the Text widget.)

example

How can I get 'abcd\n', instead of 'abc\n'?


[Solved]

Thanks to Bryan Oakley and Yasser Elsayed, I solved the problem by replacing

self.bind('<Key>', self.print_contents)

to the following:

self.bind('<KeyRelease>', self.print_contents)

example2

Upvotes: 1

Views: 1065

Answers (1)

yelsayed
yelsayed

Reputation: 5532

This is due to the timing of your event handler, which executes as soon as the event happens, meaning there was no chance for the Text widget to actually get the key typed just yet. You have two options here, either simply append the key parameter you get in the event handler to the Text.get() result, or bind to <KeyRelease-A> for example if you're listening for a specific key (A in this case).

Upvotes: 2

Related Questions