セレクションとクリップボード

アプリケーション間の情報交換ための汎用の手段として、コピー&ペーストがあります。
Tkには、コピー&ペーストを処理するコマンドに、selectionとclipboardの2つがあります。

selection

selectionコマンドは、ウィンドウの選択範囲に関する操作を行います。
オプションはすべて省略可能で、-displayofは、ウィンドウのパスを指定する。
-selectionは、PRIMARY, CLIPBOARDのいずれかで、デフォルトはPRIMARY
-typeは、STRING, ATOM, INTEGERのいずれかで、デフォルトはSTRING

# 選択範囲を解除する
selection clear -displayof window -selection selection
# 選択範囲の文字列を取得する
selection get -selection selection -type type
# 選択範囲のあるウィンドウのパスを取得する
selection own -displayof window -selection selection

clipboard

clipboardコマンドは、クリップボードに関する操作を行います。
オプションはすべて省略可能で、-displayofは、ウィンドウのパスを指定する。
-typeは、STRING, ATOM, INTEGERのいずれかで、デフォルトはSTRING

# クリップボードをクリアする
clipboard clear -displayof window
# クリップボードへ文字列を追加する
clipboard append -displayof window -type type string

仮想イベント

テキストWidgetとエントリWidgetは、標準でコピー&ペーストのための仮想イベントを持っています。
通常、コピーはCtrl+C、カットはCtrl+X、ペーストはCtrl+Vにバインドされています。
テキストWidgetのコピー&ペーストの仮想イベントの定義は以下のようになっています。

bind Text <<Copy>> {
    tk_textCopy %W
}
bind Text <<Cut>> {
    tk_textCut %W
}
bind Text <<Paste>> {
    tk_textPaste %W
}
# コピー
proc tk_textCopy w {
    if {![catch {set data [$w get sel.first sel.last]}]} {
	clipboard clear -displayof $w
	clipboard append -displayof $w $data
    }
}
# カット
proc tk_textCut w {
    if {![catch {set data [$w get sel.first sel.last]}]} {
	clipboard clear -displayof $w
	clipboard append -displayof $w $data
	$w delete sel.first sel.last
    }
}
# ペースト
proc tk_textPaste w {
    global tcl_platform
    catch {
	if {[string compare $tcl_platform(platform) "unix"]} {
	    catch {
		$w delete sel.first sel.last
	    }
	}
	$w insert insert [selection get -displayof $w -selection CLIPBOARD]
    }
}

上記例では、コピーとカットで選択範囲の文字列を取得するのに、テキストWidgetのgetコマンドを使っています。
下記の様にselectionコマンドを使って同様の処理を記述できます。

# コピー
proc tk_textCopy w {
    if {![catch {set data [selection get -displayof $w]}]} {
	clipboard clear -displayof $w
	clipboard append -displayof $w $data
    }
}