Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Radiobuttons 1

Status
Not open for further replies.

ahjoyn

Programmer
Sep 23, 2003
1
US
Could someone please tell me what I'm doing wrong here?
I am simply trying to use a value from 2 to 10 that can be selected from radiobuttons into the variable snps. But when I run the script, select the button, and look in the output file it is simply outputs 0. Thanks!

set snps 0
foreach i {2 3 4 5 6 7 8 9 10} {
radiobutton $w.rb$i -text $i -variable snps -relief flat -value $i
pack $w.rb$i -side left
}
set out1 [open "c:/test.txt" w]
puts $out1 $snps
close $out1
pack [label $w.$snps -textvariable snps -bg white]
 
I actually talked ahjoyn through this in detail, but I thought I'd post the fixed code here in case anyone else was interested.

Basically, rather than saving the value of snps to a file immediately after creating the radiobuttons, we want to create an event handler to that that whenever a user clicks one of the radiobuttons. You accomplish this with radiobuttons (and indeed, all types of Tk buttons) by providing the event handler as the button's -command value. Tcl stores this script away in memory, and then when the user clicks on the button, it pulls it out and executes it.

For an event handler longer than even a single line of code, I recommend creating a procedure, and then calling the procedure as the event handler. This simplifies a lot of the scoping and substitution issues that often trip up Tcl novices. So, here's the changed version of the script that I suggested:

Code:
proc saveValue {} {
    global snps

    set out1 [open "c:/test.txt" w]
    puts $out1 $snps
    close $out1
}

set snps 0

foreach i {2 3 4 5 6 7 8 9 10} {
    radiobutton $w.rb$i -text $i -relief flat         -variable snps -value $i         -command saveValue

    pack $w.rb$i -side left
}

# Note: corrected a slight typo on the following line,
# removing the second "$" from $w.$snps

pack [label $w.snps -textvariable snps -bg white]

- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting, 866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top