Perl/TkFAQ-10.18.如何限制输入框中内容的宽度

王朝perl·作者佚名  2008-05-18
窄屏简体版  字體: |||超大  

原文:

10.18. How do I limit an Entry's insertion width?

[OBSOLETE; explain use of new -validatecommand with 8.0] Nick Ing-Simmons recommends writing a new Entry widget with the insert method appropriately overridden by one that does limit the width. His code is avaialable as a separate package from: http://www.perltk.org/contrib/etc/LEntry-0_00.tar.gz

Now Brent Powers points out a possible problem with that approach and recommends an insert() method as follows: Date: Thu, 22 Aug 1996 10:32:44 -0400 From: "Brent B. Powers" <powers@ml.com> Subject: Re: How to set max characters for Entry widget In-reply-to: <199608211445.PAA09248@pluto> Ummm, before we set this into the distribution or FAQ, maybe we should make it work properly. An example: Imagine maxwidth configured to 8, the user fills in ABCDEFGH, moves the cursor back 4 places, and types I. The SUPER::insert call sets the string to ABCDIEFGH, which this code then modifies to ABCDIEFG. Hmmm, how about sub insert { my($w, @args) = @_; my($max) = $w->cget(-maxwidth); my($sval) = $w->get; if (length($sval) >= $max) { $w->SUPER::insert(@args); if (length($w->get) > length($sval) { ## Reject it; my($idx) = $w->index('insert'); # get current cursor position $w->delete(0, 'end'); $w->insert(0, $sval); $w->icursor($idx); $w->bell; } else { $w->SUPER::insert(@args); } } Of course, that still doesn't deal with the selection, but ...

To which Nick Ing-Simmons responded (Thu Aug 22 1996): 'paste' and <ButtonRelease-2> call insert method, what other selection issues are there?

译文:

10.18. 如何限制输入框中内容的宽度?

【Perl/Tk的作者Nick Ing-Simmons曾经建议重写一个新的Entry组件——适当的重载它的insert方法以便可以限制宽度。】

下面是Brent Powers为实现此功能提供的一个insert()方法,并且指出了其可能存在的问题:

日期: Thu, 22 Aug 1996 10:32:44 -0400

发自: "Brent B. Powers" <powers@ml.com>

主题: Re: 如何设置Entry中的最大字符数目?

In-reply-to: <199608211445.PAA09248@pluto>

嗯,在我们把下面的代码加入到“常见问题”中去前,也许我们应该先把它修正的更好一些。

一个例子:假设maxwidth选项已经被设置为8,用户先键入了ABCDEFGH,然后移动光标到, moves

第四个字符后面,键入了I。SUPER::insert的调用将使此字符串变成了ABCDIEFGH,但是下面

的代码将会把他更正为ABCDIEFG.

嗯,怎么样?

sub insert {

my($w, @args) = @_;

my($max) = $w->cget(-maxwidth);

my($sval) = $w->get;

if (length($sval) >= $max) {

$w->SUPER::insert(@args);

if (length($w->get) > length($sval) {

## Reject it;

my($idx) = $w->index('insert'); # get current cursor position

$w->delete(0, 'end');

$w->insert(0, $sval);

$w->icursor($idx);

$w->bell;

} else {

$w->SUPER::insert(@args);

}

}

当然,这里还没有考虑字符选择的问题,但是……

对此,Nick Ing-Simmons作出了回答(Thu Aug 22 1996):

'粘贴'和<ButtonRelease-2>会调用insert方法,此外还有什么其它“选择”的问题呢?

(译者注:在Tk8.0以后,似乎可以通过设置-validateCommand选项来实现此功能吧。有兴趣的朋友可以自己参考一下Entry的手册:perldoc Tk::Entry)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航