Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Making a button execute a command: Tk

by Andrew_Levenson (Hermit)
on Jan 12, 2007 at 21:48 UTC ( #594466=perlquestion: print w/replies, xml ) Need Help??
Andrew_Levenson has asked for the wisdom of the Perl Monks concerning the following question:

I'm back to working on my calculator again, and I decided to take a new approach using a loop to create buttons instead of writing every button.

How do I get Tk to execute a string of code following "command?" I've tried everything i've come up with.
for(0..9){ $input=$_; $_ = $left_num -> Button( -text => "$input", -background => 'grey', -width => 5, -height => 2, -command => $number=$number==0||$equals!=0?$input:$number.$in +put, ) -> pack(); }

Thanks in advance!
C(qw/74 97 104 112/);sub C{while(@_){$c**=$C;print (map{chr($C!=$c?shift:pop)}$_),$C+=@_%2!=1?1:0}}

Replies are listed 'Best First'.
Re: Making a button execute a command: Tk
by eff_i_g (Curate) on Jan 12, 2007 at 22:00 UTC
    At that very moment when being defined, or later, when called? Have you tried an anonymous sub?
    -command => sub { $number=$number==0||$equals!=0?$input:$number.$input + },
    Update: See the docs @ Tk::Button and follow the "Perl/Tk callback" link.
Re: Making a button execute a command: Tk
by johngg (Abbot) on Jan 12, 2007 at 23:00 UTC
    For laying out your number buttons you might want to investigate the grid geometry manager rather than using pack. As the name suggests, it allows you to lay buttons out in rows and columns more easily than pack can. You don't have to use one or the other exclusively but can mix them as appropriate. I have found it useful to lay out frames in my main window using pack to get them in the right relationship to each other and then to populate them with the buttons and other widgets I need. You can place buttons using grid in a frame that you have packed.



Re: Making a button execute a command: Tk
by zentara (Archbishop) on Jan 13, 2007 at 11:17 UTC
    #!/usr/bin/perl use warnings; use strict; use Tk; my $mw = new MainWindow; my %button; foreach my $num (0..9){ $button{$num} = $mw -> Button( -text => $num, -background => 'grey', -width => 5, -height => 2, # -command => $number=$number==0||$equals!=0?$input:$number.$in +put, -command => sub{ print "$num\n"; #do whatever here } ) -> pack(); } MainLoop;

    I'm not really a human, but I play one on earth. Cogito ergo sum a bum

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://594466]
Approved by eff_i_g
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2017-03-28 20:59 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (341 votes). Check out past polls.