Edit page: http://wiki.tcl.tk/edit/13633@ ----- '''Other pages in this series''' - [100 useful basic TCL/TK commands for simple editors 31-60] - [100 useful basic TCL/TK commands for simple editors 61-100] ----- ''' Quick Index''' * 1) How to '''start''' a procedure * 2) How to '''comment''' your code (meaning what will be commented won't be executed by the code) t '''Variables''' * 3) How to set up a '''variable''' (this is needed when we expect a feedback, a choice from the user) * 4) How to access a '''variable''' containing information given by the user '''Miscellaneous''' * 5) How to write an '''if''' statement * 6) How to put a '''negative statement''' (is not equal to) * 7) How to display a '''yes/no GUI dialog box'''? * 8) '''Synthesis of 3-7''' (3-7 in full context). How to create a yes/no box, ask user for an answer and compute the user's answer''' (Thanks [MG] for the excellent code!) * 9) How to add a '''cancel''' to your yes/no dialog box * 10) How does the '''if-else''' statement work?'''. We'll use Mike [MG]'s example in # 9. * 11) How does the '''return''' command work? * 12) How to ask the program to perform an operation when the user clicks on the '''X''' (close/quit window button) on the window title bar * 13) How to create a '''GUI dialog box''' with some text '''Function boxes''' * 14) How to call the Windows '''open page box''' and call '''text files''' * 15) How to call the Windows '''open page box''' and call '''all types of files''' * 16) How to call the '''open page box''' and to specify on which '''directory''' the program should look for files * 17) How to call other function boxes '''Miscellaneous''' * 18) How to write a line on the screen. Hey we forgot the famous puts command! How dare we! * 19) How to repeat a function until something happens (while) * 21) How to simplify the starting and completing of tcl programs. ----- '''Presentation''' [Robert Abitbol] What follows is a list of a 100 useful TCL/TK commands to write simple editors. Since I am a beginner, please don't be shy and don't hesitate to contradict me if what I am saying is wrong! I am here to learn. Thanks! This page is not reserved to me. Anyone can write anything. This is wiki! So you are all welcome to join in on the '''fun to teach TCL/TK'''. But remember: easy stuff first! This is aimed at complete ignoramuses like me.. '''Special thanks''' to Mike [MG] who has been a great help all along the way.. Mike, you'd be a great professional programming teacher... You are already a great programming teacher... ----- '''Other lists of basic commands like this one are very needed''' I strongly encourage other writers to write similar lists of basic TCL/TK commands but for other types of apps in their own domain of expertise: games, animations, drawings, mathematics, accounting, databases etc. There are a lot of scripts here on wikit but unfortunately very few basic examples to learn the basic syntax. ----- '''Should the title be: 100 useful basic TCL/TK formulas; or procedures or commands?''' [AM](16 february 2005) Just a matter of idiom: the common word for this seems to be ''idiom'' - formula makes me think of magic incantations or pseudo-scientific inventions in old movies :) [RA2] Would the word "procedures" be better, Arjen? [aricb] No, the word "procedure" is a specific term in Tcl (and many other programing languages). For Tcl, it's the thing you define with the [[proc]] command. ----- '''See also''' [MG] See also [Bag of Algorithms], [Example Scripts Everybody Should Have], and all the other pages mentioned on those two. ----- '''Recommendation''' I strongly recommend the excellent [ML tk Text Editor] to work on your TCL/TK code. See comments on that page. ----- '''1) How to start a procedure''': proc chk_exit {} { put "your instructions here" } --> chk_exit is the name of your procedure Read [proc] for more details. Remember that if you want to pass arguments to the procedure, the name of the argument goes inside the first {} . Also note that the { of the body of the proc cannot be on a seperate logical line. If you want to code the other way, you have to do something like: proc chk_exit {} \ { } ----- '''2) How to comment your code (meaning what will be commented won't be executed by the code)''' ---> Use "#" proc chk_exit {} { # this function will ask the program to ... } ----- '''VARIABLES''' '''3) How to set up a variable (this is needed when we expect a feedback, a choice from the user).''' ---> Use "set" proc chk_exit {} { set ans } '''See # 8 for the function in full context''' [MG] Although '''set''' ''is'' used to create variables, that's not actually what this example above does. The '''set''' command can take either one or two arguments. If it has one argument (like it does above), it just returns the value of the variable currently, it doesn't change it. (So, the above would raise an error because the variable ''ans'' isn't set.) proc chk_exit {} { set myvar "string" ;# sets the value of "myvar" to "string" puts [set myvar] ;# prints the value of the variable "myvar" to standard output puts $myvar ;# same as above } Or, one _might_, if ans were in some other namespace, like the global namespace, say: proc chk_exit() { set ::ans } ----- '''4) How to access a variable containing information given by the user''' Use "$" + name of the variable puts $ans ---> assuming that $ans contains the answer given by the user to a question. '''See # 8 for the function in full context''' ----- '''5) How to write an if statement''' if { $ans == "yes" } { exit } ----> if: opening brace; if the user's answer is "yes"; closing brace ----> consequence: opening brace; perform exit; closing brace '''See # 8 for the function in full context''' [MG] There are other styles for ''if'' statements, too; some people prefer to include the '''else''' and '''then'' words, too. For instance, if { $a == $b } then { puts "a and b are the same" } else { puts "a and b are different" } It all works the same, though :) ----- '''6) How to put a negative statement (is not equal to)''' --> Use "!=" if { $ans != "no" } { exit } };# chk_exit '''See # 8 for the function in full context''' ---> if { $ans != "no" } means if the user's answer is not no ... (in other words if it is yes). [MG] You can also use ''<'' for less than, ''>'' for greater than, and ''<='' and ''>='' for GTE/LTE. ----- '''7) How to display a yes/no GUI dialog box?''' set ans [tk_messageBox -type yesno -icon question -message "Are you sure you want to quit?"] '''See # 8 for the function in context''' ----- '''8) Synthesis of 3-7 (3-7 in full context). How to create a yes/no box, ask user for an answer and compute the user's answer''' (Thanks [MG] for the excellent code!) proc chk_exit {} { set ans [tk_messageBox -type yesno -icon question -message "Are you sure you want to quit?"] if { $ans != "no" } { exit } };# chk_exit ----- '''9) How to add a cancel to your yes/no dialog box?''' ---> Add cancel to - type yesno This one is so easy I guessed it! :-) That tells you how intuitive TCL is! set ans [tk_messageBox -type yesnocancel -icon question -message "Are you sure you want to quit?"] [MG] ''yesnocancel'' type boxes are often seen in programs for things like this (shown when you exit the program) set ans [tk_messageBox -type yesnocancel -icon question \ -message "Save before exiting?"] if { $ans == "cancel" } { return; } elseif { $ans == "yes" } { save } exit; ----- '''10) How does the if-else statement work?'''. We'll use Mike [MG]'s example in # 9. It works the same way as the if statement: ---> elseif: opening brace; if the user's answer is "yes"; closing brace ----> consequence: opening brace; perform save; closing brace proc chk_exit {} {} set ans [tk_messageBox -type yesnocancel -icon question \ -message "Save before exiting?"] if { $ans == "cancel" } { return; } elseif { $ans == "yes" } { save } exit};# chk_exit ----- '''11) How does the return command work?''' [MG] What it does is stop a procedure from running, possibly returning a value as the result of that procedure. You can also do more advanced things with, like also return a special code, but I think that's probably more than was intended for here originally; it's all documented on the [return] page, though, I believe. For example... proc spell {myArg} { if { $myArg == "1" } { return "one" } elseif { $myArg == "2" } { return "two" } else { return; } } set word 1 set spelling [spell $word] if { $spelling == "" } { puts "Couldn't spell $word" } else { puts "$word is spelt $spelling" } When you run [[spell 1]], at ''return one'', the spell proc returns the value of "one" and stops running. ---> See # 10. If the user has chosen cancel, nothing happens... ----- '''12) How to ask the program to perform an operation when the user clicks on the X (close/quit window button) on the window title bar''' wm protocol . WM_DELETE_WINDOW chk_exit ---> This line should go at proc.main for example. In this example, the chk.exit procedure (see # 9) will be performed when the user will click on the X on the top right of the screen. Very handy function this wm protocol! ----- '''13) How to create a GUI dialog box with some text''' - Calling a box with a text: easy! Ex: tk_messageBox -message "Sorry, this function isn't ready yet." The full function would be: proc preferences {} { tk_messageBox -message "Sorry, this function isn't ready yet. Come back later :-)" } [phk] How about this: proc preferences {text} { tk_messageBox -message $text } then you can call it from different places, using appropriate texts. The proc name could be possibly changed to messageBox (makes it more universal). Have a look at the tutorials. [MAK] Or, hey, to make it really universal, how about tk_messageBox and make it take optional switches and... oh wait. (I too am puzzled by the purpose of a proc called "preferences" that displays a dialog box saying the function isn't ready yet, as a "full" function.) Why not "notImplemented"? But, really, why would "messageBox $text" be better than "tk_messageBox -message $text"? A "proc puts_error { text } { puts stderr $text }" would be about as useful. [phk] Sure, but I think [Robert Abitbol] just started to learn tcl. My part is supposed to help him to the next level. [RS] As this is just a case of currying, one could also use interp alias {} messageBox {} tk_messageBox -message interp alias {} puts_error {} puts stderr ----- '''FUNCTION BOXES''' '''14)''' How to call the Windows open page box and call different types of files''' [MG] steals this example straight from the ActiveTcl docs on Windows set types { {{Text Files} {.txt} } {{TCL Scripts} {.tcl} } {{C Source Files} {.c} TEXT} {{GIF Files} {.gif} } {{GIF Files} {} GIFF} {{All Files} * } } set filename [tk_getOpenFile -filetypes $types] if {$filename != ""} { # Open the file ... } [MG] Just delete any lines you don't want out of the 'set types ...' to limit the filetypes. Not giving the -filetypes option at all will (on Windows only?) default to "All Files". Also, tk_getOpenFile is meant for files that already exist. If you're trying to find out where someone wants to save something, use tk_getSaveFile. ----- '''15) How to call the open file box and to specify on which directory the program should look for files''' (the program opens the directory specified by the programmer; here no choice is given to the user) ---> This is in fact simply an open file box but in a directory specified by the programmer proc open_preset_directory{} { set f [tk_getOpenFile -parent . -title "Open file" -filetypes {{All Files} * }] { } Now where do I put the name of the directory that opens when the user clicks on the function? Here it is not a choice (like # 16) so I did not set a variable. Do I use cd ... set cd..? ----- '''16) How to ask the user to choose a new directory. If the directory does not exist, the user can create it. We have the message: choose directory or create a new one on the directory box''' proc ask_user_for_directory {} { set start [pwd] set dir [tk_chooseDirectory -initialdir $start] cd $dir } '''Line by line comments by Mike [MG]''' * '''set start [pwd]''': it sets the variable ''start'' to the current working directory (which is what [pwd] returns). [RA2] Mm! '''Well explained!''' ("wd" is working dictionary) * '''set dir [tk_chooseDirectory -initialdir $start]''': it runs the tk_chooseDirectory command, which pops up a dialog box asking the user to select a directory, storing the answer in the ''dir'' variable. (With the ''-initialdir $start'' specified, the directory $start is automatically selected). tk_chooseDirectory returns the directory selected, or an empty string ("") if the user clicked Cancel. * '''cd $dir''' We change the directory to whatever the user selected, with the [cd] command. (cd means change directory; the very same command was used by DOS to change a directory). ----- '''17) How to call other function boxes''' ----- '''18) How to write a line on the screen''' Hey we forgot the famous puts command and we did not start with the famous "Hello world"! How dare we! :-) ---> Use puts ----- '''19) How to repeat a function until something happens'''' ---> Use while In this procedure we'll ask the user to guess my name. We'll keep on asking until he/she comes up with the name "Robert" then we'd say: "Good choice! My name is indeed Robert" (we'll put a quit command so the user won't spend 4 years trying to figure out my name!). ----- '''20) How to repeat a function until something happens, count the number of tries and give a message after a certain number.''' ---> Set a counter using the ... function Same as 19 + we'll ask the user if he/she wants to quit after 4 failed tries... Hey we're getting brave programming wise here! :-) ----- '''21) How to simplify the starting and completion of tcl programs.''' ---> use the rmmadwim command defined in TIP 131. This command takes no arguments, and returns the value intended by the programmer. It is very fast, because it calls a C function TclDoWhatIsMeant() with the programmer's intentions. ----- '''22) How to put a sort of device to let the program know that the user has typed in a character; so that the program will ask the user if he/she wants to save when he exits''' And of course if the user did not enter one single character, the program will exit without asking him the question: do you want to save? ----- - '''More to come. If there is an emergency, call 911. :-)''' ----- [Category Tutorial]