I received a request today for running MCE with Tk and displaying a progress bar. Your post was very helpful. Thank you.
use strict;
use warnings;
use threads;
use threads::shared;
use Tk;
use Tk::Font;
use Tk::ProgressBar;
use MCE;
# Shared variables
my $percentage_completed : shared = 0.0;
# Globals
my $percentage_label = 0.0;
my $download_label = "Completed...$percentage_completed%";
# Main Program
my $mce_thread = threads->create(\&run_mce);
run_gui();
# Subroutines
sub indicator {
my ($current_line, $total_lines) = @_;
$percentage_completed = sprintf '%.1f', $current_line * 100 / $tot
+al_lines;
}
sub run_mce {
my $n=10;
my $mce = MCE->new(
max_workers => 1,
init_relay => 0,
sequence => [ 0, $n ],
chunk_size => 1,
user_func => sub {
my ($mce, $i, $chunk_id) = @_;
MCE::relay { indicator($i, $n) };
sleep 1;
}
)->run;
}
sub run_gui {
my $mw = MainWindow->new(-title => 'Downloading...');
my $message = $mw->Message(
-textvariable => \$download_label,
-width => 130,
-border => 2
)->pack(-side => 'top');
$mw->geometry('350x100');
$mw->resizable(1,0);
my $progress = $mw->ProgressBar(
-width => 15,
-from => 0,
-to => 100,
-blocks => 50, #more block more smooth
-gap => 1, #use 0 to get solid bar else use 1
-colors => [ 0, '#104E8B' ],
-variable => \$percentage_label
)->pack(-fill => 'x');
my $button = $mw->Button(
-text => 'Cancel (ESC)',
-command => sub {
($percentage_completed < 100.0)
? MCE::Signal::stop_and_exit('TERM')
: $mw->destroy;
}
)->pack(-side => 'right');
$mw->bind('<Escape>' => sub { $button->invoke });
$mw->repeat(100 => \&update_gui);
MainLoop;
}
sub update_gui {
$percentage_label = $percentage_completed;
$download_label = "Completed...$percentage_completed%";
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.