2
\$\begingroup\$

I've written a small Tcl/Tk script for a friend that displays the current time, as well as a quote. He uses it in some project with a Raspberry Pi, and since I didn't want to cobble up something up in Qt, PyQt, or some kind of website, I tried to write something in Tcl/Tk.

Demo

Here is how it looks in the end:

screenshot of program

Requirements

This script assumes that you have fortune available an in your $PATH.

Script

#!/usr/bin/env tclsh

proc every {ms body} {
    eval $body
    after $ms [info level 0]
}

label .time -bg black -fg white -font {Arial 150} -textvar ::time -pady 30
every 1000 { set ::time [clock format [clock sec] -format "%T"] }

label .fortune -bg black -fg white -font {Arial 15}  -textvar ::fortune
every 30000 { set ::fortune [exec fortune -s] }

pack .time -fill both
pack .fortune -fill both -expand 1

. configure -bg black

wm attributes . -fullscreen 1

bind . <q> exit

What to review

This is my first script in Tcl/Tk. Feel free to commend on anything, especially if there's some kind of common style I'm missing.

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Nice code. I only see a couple of items

  1. add package require Tk to be explicit you need tk
  2. use uplevel #0 $body instead of eval
\$\endgroup\$
4
  • \$\begingroup\$ Ad 1) I had that in the original Raspberry code and another rewrite, completely missed it in my last one. ad 2) can you explain the difference between uplevel #0 $body and eval? \$\endgroup\$
    – Zeta
    Commented Feb 1, 2018 at 20:09
  • \$\begingroup\$ uplevel evaluates the given code in a particular "stack frame". This is important as each frame the current execution stack will have a different set of (local) variables. The level #0 is the zero-th level from the bottom of the stack, in other words the global frame. In your programming, you are explicitly setting global variables, so eval and uplevel #0 have identical effects. \$\endgroup\$ Commented Feb 1, 2018 at 21:35
  • \$\begingroup\$ where uplevel is really handy is in writing custom loops like myforeach foo $list {some body here} where you need to evaluate the loop body 1 level up in the stack frame (where the myforeach command invocation resides) \$\endgroup\$ Commented Feb 1, 2018 at 21:41
  • \$\begingroup\$ Is there some kind of style guide? Or does "usual" Tcl code look like mine? \$\endgroup\$
    – Zeta
    Commented Feb 6, 2018 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.