1

使用 Perl Tkx,我想从用户那里得到一些输入,关闭窗口,也许以后再做一次。对于用户输入,我只是显示一些按钮,用户可以点击其中一个。这是我现在拥有的:

sub prompt_user {
  my $answer;
  my $mw = Tkx::widget->new(".");   ## the main window is unavailable the second time
  $mw->g_wm_title("Window Title");  ## line 40
  $mw->g_wm_minsize(300, 200);

  my $label = $mw->new_label( -text => "Question to the user?");
  $label->g_pack( -padx => 10, -pady => 10);

  my $button1 = $mw->new_button(
          -text => "Option One",
          -command => sub { $answer = 0; $mw->g_destroy; },
         );
  $button1->g_pack( -padx => 10, -pady => 10);
  my $button2 = $mw->new_button(
          -text => "Option Two",
          -command => sub { $answer = 1; $mw->g_destroy; },
         );
  $button2->g_pack( -padx => 10, -pady => 10);
  Tkx::MainLoop();     ## This blocks until the main window is killed

  return $answer;
}

因此,用户单击其中一个按钮,窗口关闭,prompt_user() 返回 0 或 1(取决于用户单击了哪个按钮),然后继续执行。直到我再次尝试提示用户。然后我得到一个错误:

can't invoke "wm" command:  application has been destroyed at MyFile.pm line 40

我只是想要一种放置一堆按钮的方法,让用户单击一个,等待查看哪个被单击,也许稍后再做一次。有没有一种方法可以在不破坏主窗口的情况下等待对按钮单击的响应?也许创建一个子窗口?

我是使用 Tkx 的新手,谷歌搜索显示了很多简单的例子,比如上面的代码(使用 MainLoop/g_destroy),但我找不到任何重新创建窗口的例子。我确实看到了有关对话框或消息框的内容,但这些内容不适合我的需要。我想在按钮上放置文本,并使用任意数量的按钮(所以我不想被限制为是/否/取消,只有 3 个选项)。

更新 这是我能够使用的

# hide the main window, since I'm not using it
my $mw = Tkx::widget->new(".");
$mw->g_wm_withdraw();

# function to prompt the user to answer a question
# displays an arbitrary number of answers, each on its own button
sub prompt {
  my $prompt = shift;
  my $list_of_answers = shift;

  # Note:  the window name doesn't matter, as long as it's './something'
  my $answer = Tkx::tk___dialog( "./mywindowpath", # window name
        "Prompt",            # window title
        $prompt,             # text to display
        undef,               # tk bmp library icon
        undef,               # default button
        @$list_of_answers);  # list of strings to use as buttons

  return $answer;
}

# use the button to ask a question
my $index = prompt("Who was the best captain?",
                   [ "Kirk", "Picard", "Cisco", "Janeway", "Archer" ] );
4

1 回答 1

2

我对 Tkx 不是很熟悉,但 Tk 并不能很好地工作。一般来说,Tk 应用程序是异步的。您应该根据回调(类似于 javascript)重新编写您的应用程序。

基本上,这种逻辑:

sub do_something {

    perform_some_action();

    my $result = prompt_user();

    perform_some_other_action($result);
}

应该重写为:

sub do_something {

    perform_some_action();

    prompt_user(perform_some_other_action);
}

你的程序基本上不应该有主循环。Tkx::MainLoop相反,程序末尾的调用成为主循环,您应该通过处理事件来完成所有处理。

话虽如此,有一些可用的机制可以模拟阻塞。阅读文档vwait。不过,我认为即使这样也需要运行Tkx::MainLoop,因此不一定能避免重构整个程序。

关于如何创建和销毁窗口的问题有两种解决方案:

  1. 使用主窗口 ( .) 但不要在最后销毁它。而是隐藏它并摧毁它的所有孩子。然后,您可以稍后.通过取消隐藏来重用它。

  2. 隐藏.并且不要使用它。而是创建其他窗口(顶层)并使用它们。由于顶层是.它们的子级,因此可以安全地销毁它们而不会搞砸 Tk。

于 2010-12-07T04:13:03.940 回答