Widget hierarchy ASCII tree

MEd 2006/02/21: This may be useful for debugging purposes. All widgets which are hierarchically below a given widget (default = root) are displayed in tree format on stdout.

The procedure can be easily adapted to show more detailed information for each widget (e.g. bind and bindtags info).

 # Name: wlist.tcl
 # Author: Martin Eder, [email protected]
 # Description: All widgets which are hierarchically below a given widget
 #      (default = root) are displayed in tree format on stdout.

 package require Tk
 
 proc wlist {{top {.}} {in {}} {rec {0}}} {
    set in "$in |"
    set children [winfo children $top]
    set cnt 0
 
    if {!$rec} {puts "$top"}
    foreach child $children {
       incr cnt
       if {$cnt == [llength $children]} {
          set in "[string replace $in end-1 end] "
          puts "$in\\\__$child"
       } else  {
          puts "$in\__$child"         
       }      
       wlist $child $in 1
    }
 }
 
 proc demo {} {
    ### Creating some nested GUI
    pack [button .b1 -text "Just"] [button .b2 -text "Testing"] -pady 5
    pack [frame .f1 -relief groove -borderwidth 2 -padx 5 -pady 5] -fill both -padx 5 -pady 5
    pack [frame .f2 -relief groove -borderwidth 2 -padx 5 -pady 5] -fill both -padx 5 -pady 5
    pack [frame .f3 -relief groove -borderwidth 2 -padx 5 -pady 5] -fill both -padx 5 -pady 5
    pack [button .f1.b1 -text "Button"]
    pack [label .f2.l1 -text "Label1"] [label .f2.l2 -text "Label2"] [entry .f2.e1 -text "B"]
    pack [frame .f3.f1 -relief ridge -borderwidth 2 -padx 5 -pady 5]
    pack [button .f3.f1.b1 -text "Child1"] [button .f3.f1.b2 -text "Child2"]
       
    puts "\nStarting with root widget:"
    wlist
    puts "\nStarting with .f3 widget:"
    wlist .f3   
 }
 
 demo
 ### End of Script

The result for this demo will look like this:

 Starting with root widget:
 .
  |__.b1
  |__.b2
  |__.f1
  | \__.f1.b1
  |__.f2
  | |__.f2.l1
  | |__.f2.l2
  | \__.f2.e1
  \__.f3
   \__.f3.f1
    |__.f3.f1.b1
    \__.f3.f1.b2

 Starting with .f3 widget:
 .f3
  \__.f3.f1
   |__.f3.f1.b1
   \__.f3.f1.b2
 %