Updated 2016-01-31 22:43:10 by HJG

Summary  edit

HJG 2016-01-28: This is a fork of A little value dialog by Richard Suchenwirth, a small edit-value-dialog.

The immediate upcoming intended use is in MINISS - Mini Spread Sheet, together with that nice and short m+-menu routine.

Description  edit

This is a custom dialog - a toplevel that prompts for a value.

I have some ideas on how to modify the original value_dialog - routine, so I made a separate page here:

  • Avoid double-returning the result (return + global var)
  • Undo/discard when pressing the Cancel-button
  • controlling the position of the dialog

...

Code edit

  package require Tk

 #
 # Input-Dialog: (from http://wiki.tcl.tk/8692 "A little value dialog" by R.Suchenwirth)
 #
 proc edit_val {string } {
    set w [toplevel .edit]
    wm resizable $w 0 0
    wm title $w "Edit cell"

    label  $w.l -text    $string
    entry  $w.e -textvar ::val -width 20
    set old  $::val

    button $w.ok     -text "  OK  " -command {set ::done 0}
    button $w.clear  -text "Clear " -command "set ::val {}"
    button $w.cancel -text "Cancel" -command "set ::val $old; set ::done 1"

    bind   $w.e <Return> {set done 1}
    bind   $w.e <Escape> "$w.cancel invoke"

    grid $w.l  -    -        -sticky news
    grid $w.e  -    -        -sticky news
    grid $w.cancel  $w.clear  $w.ok

    raise $w .
    focus $w.e

    vwait ::done
    destroy $w
    return $::done
 }

 # Demo:

 wm withdraw .
 update
 wm deiconify .;           # window-manager needs to update size and position

 set zz [wm geometry .];   # get size and position
 wm title . $zz

 set val 123;  # global var, for use with `-textvar`
 set done -1

 set res [edit_val "Enter value:"]
#puts  val:$val
 pack [ label .l -text "Result: $res --> '$val' " -pady 30 -padx 30 ]
 focus -f .

Comments edit

Features:

  • acts on the global variable val, because -textvar uses global vars.
  • uses the global variable done, because vwait uses global vars.
  • The dialog comes up on top of the parent-window, focus on the entry-field.
  • Return-key for OK.
  • ESC-key for Cancel = exit dialog with no changes.
  • Returns 0 if OK was pressed, 1 if cancel was pressed, (2+ for errors)

See also edit

  • Simple Entry Demo - Tk-demo: label, entry, button, image. Calculation, but no validation .
    Uses a simple layout with frames and pack: enter 3 numbers, show their sum and product.
  • grid - the "Basic Example" for an entry-form with several fields, using labels and entries.