Version 1 of Inserting an Entry Widget in TkTable

Updated 2005-10-27 22:56:19

EKB I needed to have a properly editable table cell in TkTable. But I still wanted the arrow keys to work for table navigation under normal circumstances. I added some bindings so that either a double mouse click or pressing ctrl-enter will pop up an edit widget in the active cell.

Here's the basic code:

 event add <<tableEditCell>> <Double-Button-1>
 event add <<tableEditCell>> <Control-Return>
 bind $table.t <<tableEditCell>> {
  # Make sure the cell is up-to-date, first
  forceupdate %W
  # Create an edit widget
  if [winfo exists %W.entry] {
    saveEntry %W
    destroy %W.entry
  }
  set row [%W index active row]
  set col [%W index active col]
  entry %W.entry -validate key -vcmd "validate %W %%P"
  bind %W.entry <KeyPress-Escape> {killEntry %W}
  bind %W.entry <KeyPress-Return> {saveEntry %W; killEntry %W; forceupdate %W}
  bind %W.entry <FocusOut> {saveEntry %W; killEntry %W; forceupdate %W}
  %W window configure "$row,$col" -window %W.entry -sticky news
  %W.entry insert end [%W get $row,$col]
  %W.entry selection range 0 end
  focus %W.entry
  break
 }

To work, it needs some application-specific procs (w is the table widget):

 proc forceupdate {w} {
   # ... Update any data structure with the cell contents
 }

 proc killEntry {w} {
   # ... Get rid of the entry widget
 }

 proc validate {w s} {
   # ... Pass the validate command to the entry widget
 }

 proc saveEntry{w} {
   # ... Take the contents of the entry widget and store in the table cell
 }

(Why did I make some of the proc names camel case and some not? Sigh... I try to be consistent, but often miss.)