问题
I'm trying to create a program with Tk that will take the data from an entry, and, at the click of a button, create a label that has that data.
Below is the code I've been debugging. In the process of debugging, I have tried tb]geh following:
- using references to
$printItem
- have the subroutine connected to
-command
go to a subroutine - combining the above in various ways
use Tk; use strict; use warnings;
$mw = MainWindow -> new;
my $printItem = $mw -> Entry(-width = 20); $printItem -> pack;
$mw -> Button(-text => "Write.", -command => sub{ $mw -> Label(-text => "$printItem") -> pack} -> pack;
MainLoop;
When I click the button, all that the label shows is Tk::Entry=HASH([seemingly random hexadecimal number here])
. This is obviously not what I want, and I'd like to know how I can get the effect I desire.
回答1:
Tk::Entry=HASH(0xdeadbeef)
is how Perl stringifies objects. And indeed, your $printItem
variable stores an object of class Tk::Entry
:
my $printItem = $mw -> Entry(-width = 20);
To get the string from a Tk::Entry widget, you can use its get method:
... -command => sub { $mw->Label(-text => $printItem->get)->pack } ...
Complete working example:
use strict;
use warnings;
use Tk;
my $mw = MainWindow->new;
my $printItem = $mw->Entry(-width => 20); $printItem->pack;
$mw->Button(-text => "Write.", -command => sub { $mw->Label(-text => $printItem->get)->pack })->pack;
MainLoop;
来源:https://stackoverflow.com/questions/56760432/how-do-i-change-the-data-in-a-label-in-perl-tk