1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
use strict; use warnings; use Tk; use Tk::Canvas; my ( $X, $Y, $dx, $dy); my $mw = MainWindow->new(-width => 500, -height => 500); my $canvas = $mw->Canvas(-width => 500, -height => 500)->place( -x => 0, -y => 0); my $Button1 = $canvas->Button( -text => "Test" )->place( -x => 10, -y => 40, -height => 24, -width => 150); $canvas->Tk::bind( '<ButtonPress-1>', sub { startmove(); } ); $canvas->Tk::bind( '<ButtonRelease-1>', sub { endmove(); } ); MainLoop; sub startmove { my $ev = $canvas->XEvent; ( $X, $Y ) = ( $ev->x, $ev->y ); $mw->Tk::bind( '<B1-Motion>', \&moveit ); } sub moveit { my $ev = $canvas->XEvent; my ( $cx, $cy ) = ( $ev->x, $ev->y ); ( $dx, $dy ) = ( $cx - $X, $cy - $Y ); my %coords = $Button1->placeInfo; $Button1->placeConfigure(-x => ($coords{-x}+$dx), -y => ($coords{-y}+$dy)); ( $X, $Y ) = ( $cx, $cy ); } sub endmove { my $ev = $canvas->XEvent; my ( $cx, $cy ) = ( $ev->x, $ev->y ); ( $dx, $dy ) = ( $cx - $X, $cy - $Y ); my %coords = $Button1->placeInfo; $Button1->placeConfigure(-x => ($coords{-x}+$dx), -y => ($coords{-y}+$dy)); }