Reputation: 614
Tcl/Tk : Is there a way to get the list of options and commands of a Tcl/Tk widget using introspection or refection from Tcl ?
I was thinking at something like the Python : X.__dict__
which returns a dictionary of properties of an arbitrary object x.
I tried info
and winfo
but it does not seem to do the trick
If is is possible to access these properties by code, it would save me the effort to code them by hand, widget by widget (I am trying to create "yet another Tcl/Tk" binding ...)
Thanks in advance !
Upvotes: 2
Views: 1992
Reputation: 1
proc saveOptions {} {
set f [open saved_defaults w+]
foreach w {button checkbutton \
radiobutton menubutton \
entry menu label spinbox \
listbox canvas scrollbar scale frame} {
set x [$w .xx]
foreach b [$x configure] {
if {[llength $b] == 2} continue;
puts $f "*[string totitle $w].[lindex $b 1]:[lindex $b end]"
}
destroy $x
}
close $f
}
Upvotes: 0
Reputation: 137557
To get the list of options for a widget, use the configure
command without extra options.
% button .b
.b
% puts [join [lmap c [.b configure ] {if {[llength $c] == 2} continue; lindex $c 0}] \n]
-activebackground
-activeforeground
-anchor
-background
-bitmap
-borderwidth
-command
-compound
-cursor
-default
-disabledforeground
-font
-foreground
-height
-highlightbackground
-highlightcolor
-highlightthickness
-image
-justify
-overrelief
-padx
-pady
-relief
-repeatdelay
-repeatinterval
-state
-takefocus
-text
-textvariable
-underline
-width
-wraplength
If you've not got 8.6, you'd instead have to do:
foreach config [.b configure] {
if {[llength $config] == 2} continue
puts [lindex $config 0]
}
# Same output
The easiest way of getting the list of subcommands (but you can call them methods if you want) is by looking at the error message.
% .b ?
bad option "?": must be cget, configure, flash, or invoke
Buttons don't have that many subcommands.
You could script that with catch
and some regexps, and the format of the message is very stylised, but there's not all that much point except interactively; code won't know when to use a method (and won't have a much better idea about how to use it). Once you've taught it that, you don't need the generic introspector so much…
All widgets will have configure
and cget
. If it doesn't, it's not a widget. Everything else depends on the class. You can get that with winfo class
, but some widgets can be mutated at creation. There's no substitute for reading the documentation… except asking specific questions here, of course.
Upvotes: 2