在 Perl-Tk 中使用 Button 小部件执行命令
#!/usr/local/bin/perl
use Tk;
# Main Window
$mw = new MainWindow;
$label = $mw -> Label(-text=>"Hello World") -> pack();
$button = $mw -> Button(-text => "Quit",
-command => sub { exit }) -> pack();
MainLoop;
在此代码中,当按下按钮 $button
时,它将关闭程序。因为它执行的是exit命令。我想修改代码,以便当用户单击按钮时它将刷新 iptables 规则(iptables -F
)。我该怎么做?
我尝试过:
$button = $mw -> Button(-text => "Flush the rules",
-command => system ( iptables -F )) -> pack();
为什么这不起作用?我是否必须为其创建一个子例程(然后在那里编写 iptables -F 命令)然后调用该子例程?我不能像上面的代码一样直接输入命令吗?
#!/usr/local/bin/perl
use Tk;
# Main Window
$mw = new MainWindow;
$label = $mw -> Label(-text=>"Hello World") -> pack();
$button = $mw -> Button(-text => "Quit",
-command => sub { exit }) -> pack();
MainLoop;
In this code when the button $button
is pressed it closes the program. Because it executes the exit command. I want to modify the code so that when the user clicks on the button it will flush the iptables rule (iptables -F
). How can I do this?
I tried this:
$button = $mw -> Button(-text => "Flush the rules",
-command => system ( iptables -F )) -> pack();
Why isn't this working? Should I have to make a subroutine for it (then writing the iptables -F
command there) and then call that subroutine? Can't I directly put the command as I did in above code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要指定一个代码引用 - 一个回调 - 将在按下按钮时执行,因此您应该将系统调用放在
sub { }
中。您编写的是在定义 Button 时对 system() 的调用,因此您将 system() 的返回值指定为回调的 coderef - 这是行不通的。 system() 函数将在定义 Button 时调用,而不是在按下按钮时调用 - 这不是您想要的。
You need to specify a code reference - a callback - which will be executed when the button is pressed, so yes you should place your system call in a
sub { }
.What you've written is a call to system() at the point that the Button is defined, so you're specifying the return value from system() as the coderef for the callback - which won't work. The system() function will be called when Button is defined, not when its pressed - which isn't what you want.