Duck Dodgers
Duck Dodgers

Reputation: 3461

Tcl/Tk absolutely simple Hello World example fails - invalid command name "button"

I was trying to follow the tutorials/code-snippets on the wiki Tcl lang page.

#! /usr/local/bin/wish
button .hello -text "Hello, World!" -command { exit }
pack .hello

it gives the following error:

$ tclsh hello_world.tcl
invalid command name "button"
while executing
"button .hello -text "Hello, World!" -command { exit }"
(file "hello_world.tcl" line 4)


enter image description here

and upon pressing retry, I get this:

enter image description here

which is not what I want.

I just wanted a simple button with "Hello World" which upon getting clicked would close the window that was launched upon executing the script/command.

Googling the term "Load Tk in Tcl" or something similar produced nothing helpful.

How to get a working example in both cases?

Upvotes: 1

Views: 1121

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

It looks like Tcl files have been configured to be run by tclsh (which doesn't load the Tk package by default) and not wish (which does load Tk). The simplest fix is to explicitly load it at the start of your script with:

package require Tk

in all cases; then you'll either get things working as you expect or you'll get a clear failure that says that Tk couldn't be loaded (instead of a more mysterious message saying there's no button command).


Canonically, the recommended way of doing this would be:

#! /usr/bin/env wish

package require Tk

button .hello -text "Hello, World!" -command { exit }
pack .hello

as that allows for wish to be found on the path rather than being hard-coded to a particular location.

Upvotes: 3

Jerry
Jerry

Reputation: 71538

You need to load Tk first, in other words:

#! /usr/local/bin/wish
package require Tk      ;# This line

button .hello -text "Hello, World!" -command { exit }
pack .hello

Upvotes: 2

Related Questions