Pygtk TextView setting cursor at the beginning
I have a gtk.TextView() and every time the user puts text in it and hit return I want to print the text in the terminal and erase everything in the text area and so, put the cursor at the beginning of the textview. I tried to :
self.textbuffer.set_text("")
or :
start, end = self.textbuffer.get_bounds()
self.textbuffer.delete(start, end)
But both these codes even if they erase the text in the text area, they don't put the cursor back on the first line but instead it is on the second line. And if I type more text and return, it always stays on the second line, I don't know the reason why.
Well I didn't manage to do it so I used a trick for the time being, here it is :
self.textview = gtk.TextView()
self.textbuffer = self.textview.get_buffer()
self.textview.connect("key_press_event", self.on_key_press_event)
and my self.on_key_press_event :
def on_key_press_event(self,widget, event):
keyname = gtk.gdk.keyval_name(event.keyval)
if keyname == "Return":
self.textbuffer = self.textview.get_buffer()
startiter, enditer = self.textbuffer.get_bounds()
print self.textbuffer.get_text(startiter, enditer)
self.textview.destroy()
self.textview=gtk.TextView()
self.sw.add(self.textview)
self.textview.show()
self.textview.grab_focus()
self.textview.connect("key_press_event", self.on_key_press_event)
So each time the user hit return I remove the textview from my gtk.ScrolledWindow , destroy it, create a new one and add it 开发者_运维百科again in my gtk.ScrolledWindow, it works but it's really dirty...
Any idea of how I can make this work without that dirty code ?
Thanks in advance,
Nolhian
Here is what is happening:
The user presses the enter key and your code is being run. The widget then takes over again and does what it always does when Return
is pressed, which is to move the cursor to the next line.
But if you bind your command to the key release event,
self.textview.connect("key_release_event", self.on_key_press_event)
then your code is executed after the cursor has been moved to the next line, so set_text("")
is all that is needed to clear the buffer and move the cursor to its start.
精彩评论