帮助< key> python Entry小部件中的事件 [英] Help with <key> event in python Entry widget

查看:194
本文介绍了帮助< key> python Entry小部件中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用python编写一些代码,尝试检索Entry小部件的内容时遇到了麻烦. 关键是:我想限制可以键入的字符,所以当我达到特定数量的字符(在这种情况下为2)时,我试图清除Entry小部件,但看起来我总是想念最后键入的字符特点.我在打印中添加了丢失的字符以显示.

I'm writing some code in python and I'm having trouble when trying to retrieve content of an Entry widget. The thing is: I want to limit the characters that can be typed, so I'm trying to clear the Entry widget when I reach the specific number of characters (2 in this case), but it looks like I always miss the last typed character. I added the lost character in a print to show.

这是示例代码:

from Tkinter import *
class sampleFrame:
    def __init__(self, master):
        self.__frame = Frame(master)
        self.__frame.pack()
    def get_frame(self):
        return self.__frame


class sampleClass:
    def __init__(self, master):
        self.__aLabel = Label(master,text="aLabel", width=10)
        self.__aLabel.pack(side=LEFT)
        self.__aEntry = Entry (master, width=2)
        self.__aEntry.bind('<Key>', lambda event: self.callback(event, self.__aEntry))
        self.__aEntry.pack(side=LEFT)

    def callback(self, event, widgetName):
        self.__value = widgetName.get()+event.char
        print self.__value
        if len(self.__value)>2:
            widgetName.delete(2,4)





root = Tk()
aSampleFrame = sampleFrame(root)
aSampleClass = sampleClass(aSampleFrame.get_frame())
root.mainloop()

任何帮助将不胜感激!

预先感谢

推荐答案

首先,在执行删除操作后,事件将继续进行常规处理,即插入字符.您需要向Tkinter发出信号,该事件应被忽略.

At first, after you do the deletion, the event goes on with its normal processing, i.e. the character gets inserted. You need to signal to Tkinter that the event should be ignored.

因此,在上面的代码中,添加标记的行:

So in your code above, add the marked line:

if len(self.__value) > 2:
    widgetName.delete(2,4)
    return "break" # add this line

另一方面,为什么要经过lambda?事件具有您可以使用的.widget属性.因此,您可以将代码更改为:

On the other hand, why do you go through the lambda? An event has a .widget attribute which you can use. So you can change your code into:

    self.__aEntry.bind('<Key>', self.callback) # ※ here!
    self.__aEntry.pack(side=LEFT)

def callback(self, event):
    self.__value = event.widget.get()+event.char # ※ here!
    print self.__value
    if len(self.__value)>2:
        event.widget.delete(2,4) # ※ here!
        return "break"

所有更改的行均标记有此处!"

All the changed lines are marked with "here!"

这篇关于帮助&lt; key&gt; python Entry小部件中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆