Vee
Vee

Reputation: 776

Tcl/Tk text widget - moving cursor to end of the text

I'm having some trouble figuring out how to move the cursor of the text widget to the end of the text in Tcl/Tk.

I'm writing a program with a text area that behaves like a command prompt or terminal - so when the user presses up, the previous commands the user entered will be re-printed at the end of the text. I have this so far:

bind .text <Up> {
   if {$prev_cmd ne ""} {
      .text insert end $prev_cmd
   }
}

This will insert the command at the end of the text - however the default behavior for the text is still in effect, so when pressing up, the cursor will move up to the previous line, which I don't want.

I've tried adding the following line after the insert command:

.text mark set insert end

but what it doesn't bring the cursor to the end of the text, rather it stays on the end of the previous line. Is this possible to do, or does the text widget not recognize that there was a new line/string added in yet?

Upvotes: 0

Views: 1194

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137727

The cursor is doing what you want. However, the class binding for the <KeyPress-Up> event, which follows your widget-specific binding, is then applying the default cursor motion event and that's moving the cursor to the previous line (which must be quite short as it happens).

Though in theory you could change the class bindings to not do this (they're just bindings on Text instead of on .text) you should not do this as you will be adjusting the behaviour of every text widget in the program, which could really surprise you. Instead, you should just prevent the event binding tag chain processing from going on to the class bindings by inserting a break.

bind .text <Up> {
   if {$prev_cmd ne ""} {
      .text insert end $prev_cmd
      break
   }
}

Other options are possible, such as making your own pseudo class bindings and attaching them with the bindtags command, but that's much more work (and comes under the heading of “advanced Tk hacking”). You'd only do it where you wanted to prevent normal class bindings without stopping later bindings (the per-toplevel and true global binding collections — . and all in your case).

Upvotes: 2

Related Questions