ZetCode

Tk clipboard and drag and drop

last modified November 24, 2026 Tcl 8.6

Copying text between applications on a desktop is done through selections. The clipboard is the selection that survives until something replaces it, and the primary selection is the text that is currently highlighted. Tk exposes both with the clipboard and selection commands.

Drag and drop is not a separate Tk feature. It is built from mouse bindings: a press records the starting point, a motion moves the dragged object, and a release decides where it landed. This article covers the clipboard, the selection, ownership and then a small drag-and-drop scene on a canvas.

The clipboard command

clipboard clear removes the current contents, clipboard append adds text and clipboard get reads it back. -type STRING asks for the plain text form. Reading an empty clipboard is an error, not an empty string.

basic.tcl
package require Tk

clipboard clear
puts "empty:   [catch {clipboard get} err] $err"

clipboard append "first part"
clipboard append " and second part"
puts "text:    [clipboard get]"
puts "STRING:  [clipboard get -type STRING]"

clipboard clear
puts "cleared: [catch {clipboard get} err] $err"

destroy .

The two append calls build one string, because appending adds to the existing contents instead of replacing them. The script prints the catch result and its message side by side, so a success shows 0 and a failure shows 1 followed by the error text. The clipboard belongs to the display, which is why the script needs wish rather than tclsh.

$ wish basic.tcl
empty:   1 CLIPBOARD selection doesn't exist or form "STRING" not defined
text:    first part and second part
STRING:  first part and second part
cleared: 1 CLIPBOARD selection doesn't exist or form "STRING" not defined

Copying and pasting text

The entry and text widgets already implement copy and paste through virtual events. Selecting text in an entry and sending <<Copy>> puts the selection on the clipboard; sending <<Paste>> to a text widget inserts it at the insertion mark.

text.tcl
package require Tk

entry .source -width 26
text .target -width 26 -height 3
pack .source .target -padx 8 -pady 6
update

.source insert 0 "copy this phrase"
.source selection range 0 9
event generate .source <<Copy>>
puts "clipboard: [clipboard get]"
puts "owner:     [selection own]"

.target insert 1.0 "Pasted: "
focus -force .target
event generate .target <<Paste>>
puts "target:    [.target get 1.0 end-1c]"

destroy .

selection range 0 9 highlights the characters from index 0 up to but not including 9, which is the text copy this. The <<Copy>> event is handled by the entry's class binding, so the script does not have to touch the clipboard itself. The paste goes to the focused widget, and the text widget's trailing newline is removed with end-1c.

$ wish text.tcl
clipboard: copy this
owner:     .source
target:    Pasted: copy this

The selection command

The primary selection is the X11 selection that follows the mouse highlight. selection own -selection PRIMARY claims it for a window, and selection handle installs a procedure that answers requests for the data. The procedure receives an offset and a maximum length and returns the matching part of the text.

selection.tcl
package require Tk

label .source -text "Primary selection source"
pack .source -padx 8 -pady 8
update

proc provide {offset maxchars} {
    set text "served by the provide handler"
    return [string range $text $offset [expr {$offset + $maxchars - 1}]]
}

selection handle .source provide
selection own -selection PRIMARY .source
puts "owner: [selection own -selection PRIMARY]"
puts "text:  [selection get -selection PRIMARY]"

selection clear -selection PRIMARY
puts "cleared: [catch {selection get -selection PRIMARY} err] $err"

destroy .

The handler is called whenever another client asks for a range, which is why it takes the offset and length instead of returning the whole string. Tk slices the text with string range and sends the answer back. After selection clear the selection no longer exists, and a read fails with the same message as an empty clipboard.

$ wish selection.tcl
owner: .source
text:  served by the provide handler
cleared: 1 PRIMARY selection doesn't exist or form "STRING" not defined

Clipboard ownership

A clipboard has no storage of its own: the application that last wrote to it keeps the data and answers requests from other programs. This is called ownership. selection own reports the owning window, and the data disappears when the owner exits.

ownership.tcl
package require Tk

puts "empty:    [selection own]"
puts "first:    [catch {clipboard get} err] $err"

selection own .
puts "claimed:  [selection own]"
clipboard append "owned by this script"
puts "text:     [clipboard get]"

clipboard clear
puts "cleared:  [selection own] / [catch {clipboard get} err] $err"

destroy .

Claiming the selection with selection own . makes the main window the owner, and clipboard append then stores the text under that claim. clipboard clear removes the text but does not release the claim, so the owner is still reported while reads fail. A second process can read the text while this one runs and finds nothing after it exits.

$ wish ownership.tcl
empty:    
first:    1 CLIPBOARD selection doesn't exist or form "STRING" not defined
claimed:  .
text:     owned by this script
cleared:  . / 1 CLIPBOARD selection doesn't exist or form "STRING" not defined

Drag sources

A drag source is a widget that starts a drag when the user presses the mouse button over it. On a canvas the binding belongs to the item, and the substitutions %x and %y pass the pointer position to the callback. The callback stores the press point, and the motion handler moves the item by the difference.

drag_source.tcl
package require Tk

canvas .c -width 280 -height 150 -background white
pack .c

set box [.c create rectangle 20 40 90 90 -fill #3a6ea5 -outline ""]
set drag_x 0
set drag_y 0

proc pick_up {x y} {
    global drag_x drag_y
    set drag_x $x
    set drag_y $y
    .c raise $::box
    puts "picked up at $x $y"
}

proc drag {x y} {
    global drag_x drag_y
    .c move $::box [expr {$x - $drag_x}] [expr {$y - $drag_y}]
    set drag_x $x
    set drag_y $y
    puts "moved to $x $y, coords [.c coords $::box]"
}

.c bind $box <ButtonPress-1>   {pick_up %x %y}
.c bind $box <B1-Motion>       {drag %x %y}

wm deiconify .
update
event generate .c <Motion> -x 50 -y 60
event generate .c <ButtonPress-1> -x 50 -y 60
event generate .c <B1-Motion> -x 110 -y 90
event generate .c <B1-Motion> -x 150 -y 100

destroy .

Each motion moves the rectangle by the distance since the previous event, so the item follows the pointer without jumping to it. raise keeps the dragged item above the others. The Motion event generated before the press is needed in the test because a canvas item receives button events only when it is the current item under the pointer.

$ wish drag_source.tcl
picked up at 50 60
moved to 110 90, coords 80.0 70.0 150.0 120.0
moved to 150 100, coords 120.0 80.0 190.0 130.0

Drop targets

A drop target decides whether a release is acceptable. It usually tests the pointer position against a rectangle and gives visual feedback, for example by filling the target while the dragged item hovers over it. The next script accepts a drop inside a fixed rectangle and rejects everything else.

drop_target.tcl
package require Tk

canvas .c -width 280 -height 150 -background white
pack .c

set box [.c create rectangle 20 40 80 90 -fill #3a6ea5 -outline ""]
set target [.c create rectangle 180 30 270 120 -fill "" -outline #2f7d4f -width 2]
.c create text 225 135 -text "drop here" -fill #2f7d4f

proc drop {x y} {
    if {$x >= 180 && $x <= 270 && $y >= 30 && $y <= 120} {
        .c itemconfigure $::target -fill #dff0e4
        puts "accepted at $x $y"
    } else {
        puts "rejected at $x $y"
    }
}

.c bind $box <ButtonRelease-1> {drop %x %y}

wm deiconify .
update
event generate .c <Motion> -x 50 -y 60
event generate .c <ButtonRelease-1> -x 220 -y 70
puts "target fill: [.c itemcget $target -fill]"
event generate .c <ButtonRelease-1> -x 100 -y 70

destroy .

The test uses the pointer position rather than the item position, because the target cares where the user let go. On an accepted drop the target is filled with a pale green, and itemcget confirms the new value. The second release at 100,70 falls outside the rectangle and is rejected without changing anything.

$ wish drop_target.tcl
accepted at 220 70
target fill: #dff0e4
rejected at 100 70

A drag-and-drop example

The full example combines the three handlers with feedback during the drag. The target is highlighted while the pointer is inside it, the drop records whether the item was accepted, and the item's final coordinates are printed after every drop.

dnd.tcl
package require Tk

canvas .c -width 300 -height 170 -background white
pack .c

set box [.c create rectangle 20 40 90 90 -fill #3a6ea5 -outline ""]
set target [.c create rectangle 190 30 280 120 -fill "" -outline #2f7d4f -width 2]
.c create text 235 135 -text "drop here" -fill #2f7d4f

set drag_x 0
set drag_y 0
set inside 0

proc pick_up {x y} {
    global drag_x drag_y
    set drag_x $x
    set drag_y $y
    .c raise $::box
    puts "drag start: $x $y"
}

proc drag {x y} {
    global drag_x drag_y inside
    .c move $::box [expr {$x - $drag_x}] [expr {$y - $drag_y}]
    set drag_x $x
    set drag_y $y
    set inside [expr {$x >= 190 && $x <= 280 && $y >= 30 && $y <= 120}]
    if {$inside} {
        .c itemconfigure $::target -fill #e8f4ec
    } else {
        .c itemconfigure $::target -fill ""
    }
}

proc drop {x y} {
    global inside
    if {$inside} {
        puts "dropped inside at $x $y"
        .c itemconfigure $::target -fill #dff0e4
    } else {
        puts "dropped outside at $x $y"
        .c itemconfigure $::target -fill ""
    }
    puts "box coords: [.c coords $::box]"
    set inside 0
}

.c bind $box <ButtonPress-1>   {pick_up %x %y}
.c bind $box <B1-Motion>       {drag %x %y}
.c bind $box <ButtonRelease-1> {drop %x %y}

wm deiconify .
update
event generate .c <Motion> -x 50 -y 60
event generate .c <ButtonPress-1> -x 50 -y 60
event generate .c <B1-Motion> -x 220 -y 70
event generate .c <ButtonRelease-1> -x 220 -y 70

event generate .c <Motion> -x 220 -y 70
event generate .c <ButtonPress-1> -x 220 -y 70
event generate .c <B1-Motion> -x 110 -y 80
event generate .c <ButtonRelease-1> -x 110 -y 80

destroy .

The inside flag is shared between the motion and the release, so the drop does not have to repeat the rectangle test. The two simulated drags show both outcomes: the first lands inside the target and leaves the box at 190,50, the second drags it back out and drops it at 80,60. A real application would move or copy data at this point, not just a rectangle.

$ wish dnd.tcl
drag start: 50 60
dropped inside at 220 70
box coords: 190.0 50.0 260.0 100.0
drag start: 220 70
dropped outside at 110 80
box coords: 80.0 60.0 150.0 110.0

Cleaning up bindings

Bindings are stored on widgets and item tags, and they stay there until they are removed. A dialog that is opened twice, or a canvas whose items are rebuilt, can collect duplicate handlers that fire twice. The fix is to remove a binding with an empty script when it is no longer needed.

cleanup.tcl
package require Tk

canvas .c -width 240 -height 120 -background white
pack .c
set box [.c create rectangle 20 20 80 70 -fill #3a6ea5 -outline ""]

bind .c <ButtonPress-1> {puts "pressed"}
bind .c <B1-Motion>     {puts "dragged"}
puts "widget bindings: [bind .c]"

bind .c <ButtonPress-1> {}
bind .c <B1-Motion>     {}
puts "after removal:   [bind .c]"

.c bind $box <Button-1> {puts "item clicked"}
puts "item bindings:   [.c bind $box]"

.c bind $box <Button-1> {}
puts "item after:      [.c bind $box]"

puts "bindtags: [bindtags .c]"
destroy .

bind .c returns the event sequences that have a script, and a removed sequence disappears from the list. Item bindings are per tag, so .c bind $box reports them separately. The last line prints the bindtag order: the widget name, its class, the toplevel and all. Removing a binding from the widget name leaves class bindings such as <<Copy>> intact.

$ wish cleanup.tcl
widget bindings: <B1-Motion> <Button-1>
after removal:   
item bindings:   <Button-1>
item after:      
bindtags: .c Canvas . all

Source

The clipboard, selection and binding commands are documented in the Tk manual, together with the canvas item bindings used for the drag source.

This article covered the clipboard and primary selections, ownership, drag sources, drop targets and a complete canvas drag-and-drop scene. Continue with Tk canvas animation, which uses the same motion events for moving items, or read about Tk images for the pictures a canvas can carry.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.