Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the Tk canvas so slow?

I wrote cellular automaton (Conway's Game of Life) using Perl and TK, just for fun and practice. It works fine with console output. When I use TK, in first version I just delete and add new cells (rectangles), and after about 100 steps my program has slowed down (about 10 times). Then I rewrote graphics part: initially made all of 2500 cells (50x50) and then changing their color instead of adding/deleting them. But after 600-700 steps my reworked automaton begins to slow down too.

This is a feature/bug of TK or I do something wrong?

Changing color by tag:

$canvas->itemconfigure("cell"."$x $y", -fill=>'blue');

Creating grid:

for($y = 0; $y < 50; $y++)
{
    for($x = 0; $x < 50; $x++)
    {
        $canvas->createRectangle($x * 10, $y * 10, ($x + 1) * 10, ($y  + 1) * 10, -fill=>'white', -tags=>["cell"."$x $y"]);
    }
}

Start and stop loop:

sub start
{
    $repeat = $MainWindow->repeat($speed, sub{&maketurn;});
    # Function "maketurn" is not important, it is a simple counting of "alive" cells
    # and changing color by tag
}

sub stop
{
    if(defined($repeat))
    {
        $repeat->cancel();
    }
}
like image 865
spyder Avatar asked Nov 13 '22 15:11

spyder


1 Answers

I found an articles about the tk canvas widget being slow with many items. The problem sounds very similar to your problem:

http://code.activestate.com/lists/perl-tk/17282/

The solution may be to use the tk photo widget which behaves much like a bitmap. This would be a little of a pain to adapt your code to but it seems like the canvas widget is inherently slow with many objects.

like image 139
floomby Avatar answered Nov 15 '22 07:11

floomby