tcl/tk

GUIは使わないのですぐ忘れる.tkを使う最低限のメモをまとめておく.

tclメモ

  • データは全て文字列として扱われる.数値の場合は読み込まれてから数値に自動で変換される.
  • 行単位のプログラミング言語で,先頭の文字列がコマンド(butonとか)
  • 変数はsetで値を代入,値を取り出すときは$を付ける.
  • 四則演算はexpr(expression式って意味かな?)の後に数式.Bashみたいだ.
  • コマンドで置換する場合は[]で囲む.
  • ウィジットの名前は"."で始める.これは"."メインウィジットを指すから.Tcl/tkのウィジット名はパス付きの名前みたいなイメージ.
set x [expr 2 + 3]        # 変数とコマンド置換の例
set y "hoge [expr 2 + 3]" # 文字列内でもコマンド置換される
button .b -text "hoge"    # オプションは'-'で指定するUnix形式

各ウィジットのメモ

全体

  • イベントとコマンドを結びつけるにはbindコマンド.
bind .widget-name event-name command

パッケージ

  • 基本的にpackerを使う.グリッドの場合のみgridderを使う.placerは使わない.
  • ウィンドウに対して余白を埋めるには-fillオプション.x,yで縦横を指定する.

ボタン

  • 重要なのはcommandオプション.おした時のコマンドを指定できる.
  • ボタンおした時,離した時でコマンド指定したい場合はbindで各イベントとコマンドを結ぶ.

ラベル(label)

  • 文字列の表示
  • textavailableオプションが重要.ここに変数を指定しておくと,変数の値に変わると自動でアップデートしてくれる.
# buton/labelの例
#! /usr/bin/wish

# label widget
set buffer "hello world!"
label .l -textvariable buffer
pack .l

# procedure for below button command
proc push_button {n} {
    global buffer
    set buffer "I push $n button."
}

# button widget
foreach i {0 1 2 3} {
    button .b$i -text "button $i" -command "push_button $i"
    pack .b$i
}
# bind example
bind .b0 <ButtonPress> {puts "hello tcl/tk"}

# exec command
button .b4 -text "pwd" -command "exec pwd &"
pack .b4

Canvas

  • 図形を描画できるウィジット.
  • create object-type coordinate [option]形式
    • line : 直線,2点(多点でも可)を指定する.
    • rectangle: 長方形,左上と右下の2点を指定.
    • oval : 円,外接する長方形の左上と右下の2点を指定.
    • text : 文字列
    • image : 図
  • 共有オプション
    • fillで塗りつぶし,outlineで枠の色,widthで枠の太さ
  • 図形へのコマンド  - move :図形を動かせる
    • bind :図形へのイベントとコマンドをバインド
    • coords :図形の座標を取得
  • バインドでは図形のIDだけでなくタグで指定できる.
# create canvas widget
canvas .c0 -width 200 -height 150
pack .c0

# create a rectangle, and name it as r0.
set r0 [.c0 create rectangle 10 10 20 20 -fill cyan]

# move r0 (above rectangle) by mouse
# B1-Motion: left click, and its coordinates can be access by %x and %y.
# 
.c0 bind $r0 <B1-Motion> {
    set x1 [expr %x-5]
    set x2 [expr %x+5]
    set y1 [expr %y-5]
    set y2 [expr %y+5]
    .c0 coords current $x1 $y1 $x2 $y2
}

.c0 bind hoge <B1-Motion> {
    set x1 [expr %x-5]
    set x2 [expr %x+5]
    set y1 [expr %y-5]
    set y2 [expr %y+5]
    # current means currently pointed object
    .c0 coords current $x1 $y1 $x2 $y2
}


# create rectangle with tag
.c0 create rectangle 20 10 30 20 -fill red -tags hoge
.c0 create rectangle 30 10 40 20 -fill blue -tags hoge
.c0 create rectangle 40 10 50 20 -fill green -tags hoge