Perl Tk 在按钮中格式化文本

Perl Tk Formatting Text in a button

下面的代码创建 Perl/Tk 按钮,其中填充了散列 %events 中每个事件的详细信息。有没有一种方法可以格式化按钮内的文本,使其以 printf 在第 16 行打印出来的方式出现在对齐的列中。

use strict;
use Tk;

my %events;
$events{"Jazz Fest"}{city}   = "New Orleans";
$events{"Jazz Fest"}{state}   = "LA";
$events{"Jazz Fest"}{date}   = "June 6th, 2023";
$events{"Lollapalooza"}{city}   = "Chicago";
$events{"Lollapalooza"}{state}   = "IL";
$events{"Lollapalooza"}{date}   = "July 25th, 2023";
$events{"Blues Fest"}{city}   = "Chicago";
$events{"Blues Fest"}{state}   = "IL";
$events{"Blues Fest"}{date}   = "Augsut 4th, 2023";

my %data;
foreach my $event (sort keys %events) {

    printf("%-15.15s %-20.20s %-2.2s %18.18s\n", $event, $events{$event}{city}, $events{$event}{state}, $events{$event}{date});
    $data{$event} = sprintf("%-15.15s %-20.20s %-2.2s %18.18s", $event, $events{$event}{city}, $events{$event}{state}, $events{$event}{date});
    
}

my $data;

my $mw = MainWindow->new;
$mw->title("Event Clipboard Copy");
$mw->label("Pick Event Details to Copy.");

for(sort keys %data){

    my $text = $data{$_};
    $mw->Button( -text => $text, -anchor => 'w', -command => sub  {
    
    Clipboard->copy( $text );
         
        }
    )->pack( -fill => 'x' );
}

MainLoop;

要对齐列,请将每个按钮的字体设置为“Courier”(或其他等宽字体)。至少有两种方法可以做到这一点:

  1. 创建按钮时
  2. 将按钮分配给一个变量,然后对其调用 configure
#Setting font when creating the button
$mw->Button( -text => $text, -anchor => 'w', -font => [-family => 'Courier'], -command => sub {
#Calling configure on the button
my $button = $mw->Button(-text => $text, -anchor => 'w', -command => sub {
...
}->pack( -fill => 'x' );
$button->configure(-font => [-family => 'Courier']);

这是将字体设置为 Courier 后的样子

并且没有设置字体: