Version 10 of A little calculator

Updated 2003-08-27 14:10:15

http://www.eteamz.com/cmym/images/calculator.jpg


Richard Suchenwirth - As yet another midnight project, here's a small calculator in Tcl/Tk. An original problem (arithmetics is done with expr, so e.g. 1/2= comes out as 0) was fixed (see discussion below). In addition to the buttons you can use any of expr's other functionalities via keyboard input. (As the screenshot shows, it runs also on a CE ;-)

 wm title . Calculator
 grid [entry .e -textvar e -just right] -columnspan 5
 bind .e <Return> =
 set n 0
 foreach row {
    {7 8 9 + -}
    {4 5 6 * /}
    {1 2 3 ( )}
    {C 0 . =  }
 } {
    foreach key $row {
        switch -- $key {
            =       {set cmd =}
            C       {set cmd {set clear 1; set e ""}}
            default {set cmd "hit $key"}
        }
        lappend keys [button .[incr n] -text $key -command $cmd]
    }
    eval grid $keys -sticky we ;#-padx 1 -pady 1
    set keys [list]
 }
 grid .$n -columnspan 2 ;# make last key (=) double wide
 proc = {} {
    regsub { =.+} $::e "" ::e ;# maybe clear previous result
    if [catch {lappend ::e = [set ::res [expr 1.0*$::e]]}] {
        .e config -fg red
    }
    .e xview end
    set ::clear 1
 }
 proc hit {key} {
    if $::clear {
        set ::e ""
        if ![regexp {[0-9().]} $key] {set ::e $::res}
        .e config -fg black
        .e icursor end
        set ::clear 0
    }
    .e insert end $key
 }
 set clear 0
 focus .e           ;# allow keyboard input
 wm resizable . 0 0

Rob Hegt - By adding the below 'fix' proc and changing the line doing the expr to the one given below, it is no longer necessary to add a . in case of a division.

 proc fix {str} {
  if {[string first "." "$str"] < 0} {
    if {[string first "/" "$str"] > -1} {
      set str "$str."
    }
  }
  return "$str"
 }

...

    if [catch {lappend ::e = [set ::res [expr [fix $::e]]]}] {

RS: Yes, but this fix raises an error with well-formed expressions like 1/(2+3). It is simpler, and more bullet-proof, to just prefix 1.0* to the expression when giving it to expr.


Arts and crafts of Tcl-Tk programming - Category Mathematics - Category Application