使用Perl,我希望从用户那里获得一些输入,关闭窗口,然后稍后再这样做。对于用户输入,我只是显示一些按钮,用户可以点击其中一个按钮。我现在拥有的是:
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,googling显示了很多简单的例子,如上面的代码(使用MainLoop/g_destroy),但是我找不到任何重新创建窗口的例子。我确实看到了有关对话框或消息框的东西,但它们不适合我的需要。我希望将文本放在按钮上,并使用任意数量的按钮(因此,我不想被限制为yes/no/cancel,只有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" ] );发布于 2010-12-07 04:13:03
我对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,因此不一定要避免重构整个程序。
关于如何创建和销毁窗口的问题,有两个解决方案:
.),但不要在最后销毁它。相反,把它藏起来,摧毁它所有的孩子。然后,您可以通过取消隐藏来重用.。.,而不使用它。相反,创建其他窗口(图解)并使用它们。由于土拨鼠是.的孩子,所以在不破坏Tk的情况下,它们是安全的。--https://stackoverflow.com/questions/4373119
复制相似问题