in reply to Adding text to a Perl/Tk canvas

Ok, here's a fish. This dosn't do it all, but it should show you everything you need to get started. After you move the text once, it is not movable again, so it won't move with the next text addition. The text will be placed at the position of the right mouse click. Since you need to press the Ok button in the dialogbox, the mouse can't have the text automatically placed on it. You can try if you want, but a right click is better. If you want something fancier, like being able to move a text a second time, figure out how to use bind and addtags. Like maybe a bind to 'Shift-ButtonPress-3' will add the 'mover' tag back onto some text.
#!/usr/bin/perl use warnings; use strict; use Tk; require Tk::DialogBox; my $dx; my $dy; my $current; my $mw = MainWindow->new; $mw->geometry("700x600"); $mw->fontCreate('big', -family=>'arial', -weight=>'bold', -size=>int(-18*18/14)); my $canvas = $mw->Canvas(-width => 700, -height => 565, -bg => 'black', -borderwidth => 3, -relief => 'sunken', )->pack; my $closebutton = $mw->Button(-text => 'Exit', -command => sub{Tk::exi +t(0)}) ->pack; my $dialog = $mw->DialogBox( -buttons => [qw/Ok Cancel/], -title => "Enter Text" ); my $dialogT = $dialog->add("Text"); $dialogT->pack(qw/-padx 10 -pady 10/); $canvas->bind('move', '<1>', sub {&mobileStart();}); $canvas->bind('move', '<B1-Motion>', sub {&mobileMove();}); $canvas->bind('move', '<ButtonRelease>', sub {&mobileStop();}); #right click to post text $canvas->Tk::bind("<ButtonPress-3>", [\&getText, Ev('x'), Ev('y') ]); MainLoop; sub getText { # print "@_\n"; my ($canv, $x, $y) = @_; my $x1 = $canv->canvasx($x); my $y1 = $canv->canvasx($y); print "$x1 $y1\n"; $dialog->configure(-focus => $dialogT); $dialog->bind('<Return>' => undef); ## Determine whether or not the user hit "Ok" my $button = $dialog->Show(); if ( $button eq "Ok" ) { my $letters = $dialogT->get( '1.0', 'end' ); #print "$letters was submitted\n"; $dialogT->delete( '1.0', 'end' ); my $dragster = $canvas->createText( $x1, $y1, -fill => 'red', -tags => ['move'], -text => $letters, -font => 'big', -anchor => 'nw', ); $current = $dragster; } } sub mobileStart { my $ev = $canvas->XEvent; ($dx, $dy) = (0 - $ev->x, 0 - $ev->y); $canvas->raise('current'); print "START MOVE-> $dx $dy\n"; } sub mobileMove { my $ev = $canvas->XEvent; $canvas->move('current', $ev->x + $dx, $ev->y +$dy); ($dx, $dy) = (0 - $ev->x, 0 - $ev->y); print "MOVING-> $dx $dy\n"; } sub mobileStop{ $canvas->dtag($current,'move'); } __END__

I'm not really a human, but I play one on earth CandyGram for Mongo

Replies are listed 'Best First'.
Re^2: Adding text to a Perl/Tk canvas
by merrymonk (Hermit) on Jun 11, 2008 at 14:15 UTC
    Thanks for that. I will see if I can modify it to get the behaviour I want.

    PS - I have found your suggestions about using tags flexibly very effective.:-)