Example

The following example illustrates a small class with several methods and some code to exercise it:

class Toaster {
        private variable toastTime 10
        constructor {} {
             puts "Toaster created"
        }
        destructor {
             puts "Toaster destroyed"
        }
        method getToastTime {} {
             return $toastTime
        }
        method setToastTime {newToastTime} {
             set toastTime $newToastTime
        }
        method toast {} {
             puts "Toaster is toasting..."
             after [expr $toastTime*1000]
             puts "\aToast is ready!"
        }
        method clean {} {
             puts "Cleaning toaster..."
             after 2000
             puts "Toaster is clean"
        }
}

puts "Starting test program"
Toaster machine
machine clean
machine setToastTime 5
puts "Toast time set to [machine getToastTime]"
machine toast
delete object machine

Get Tcl/Tk in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.