Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

Re: How to change a Tk object's property from a thread

by zentara (Archbishop)
on Aug 05, 2011 at 15:28 UTC ( [id://918805]=note: print w/replies, xml ) Need Help??


in reply to How to change a Tk object's property from a thread

Tk is not thread safe, that is why you get the GUI freeze you described in the node above. You cannot directly access a Tk widget from a thread. 

Workarounds are available. The most foolproof way is to have a shared variable in the thread which gets set to a value signalling the main Tk thread that it's time to change the button text, which ikegami showed. Tk must run a timer to watch that shared variable, here is a simpler version to demonstrate.

#!/usr/bin/perl use warnings; use strict; use threads; use threads::shared; # declare, share then assign my $ret; share $ret; $ret = 0; my $val = 0; #create thread before any tk code is called my $thr = threads->create( \&worker ); use Tk; my $mw = MainWindow->new(); my $label = $mw->Label( -width => 50, -textvariable => \$val )->pack(); my $timer = $mw->repeat(10,sub{ $val = $ret; }); MainLoop; # no Tk code in thread sub worker { for(1..10){ print "$_\n"; $ret = $_; sleep 1; } $ret = 'thread done, ready to join'; print "$ret\n"; }

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku ................... flash japh

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://918805]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2024-03-29 15:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found