2015-05-28 62 views
2

因此,在我正在编码的程序中,我将键盘上的Enter键绑定到函数。在这个函数中,光标应该移动到条目窗口小部件中文本的末尾。因此,例如,如果用户在入口窗口小部件中有122 | 57(|是光标),那么我希望此光标移动到末尾以给出12257 |。我试图达到这个目标导致了一个错误。所以,下面是我一起工作的代码:Python - 使用绑定键移动Tkinter中的条目光标

from tkinter import * 

class Calc: 
    def __init__(self,parent): 
     self.displayentry = StringVar() 
     self.display=Entry(parent, textvariable=self.displayentry) 
     self.display.pack() 

    def equal_input(self): 
     self.display.icursor(len(self.displayentry)) 

root = Tk() 
RunGUI=Calc(root) 
root.bind('<Return>', Calc.equal_input) 
root.mainloop() 

我得到一个错误,当我按下回车键,上面写着:“AttributeError错误:‘事件’对象有没有属性‘显示器’”

任何帮助将不胜感激。由于

回答

2

你应该bind()在应用程序中的事件。此外,StringVar对象没有长度 - 您首先需要get()其内容。

from tkinter import * 

class Calc: 
    def __init__(self,parent): 
     self.displayentry = StringVar() 
     self.display=Entry(parent, textvariable=self.displayentry) 
     self.display.pack() 
     parent.bind('<Return>', self.equal_input) 

    def equal_input(self, event): 
     self.display.icursor(len(self.displayentry.get())) 

root = Tk() 
RunGUI=Calc(root) 
root.mainloop() 

不过,我建议你改变你的equal_input()函数来完成,而不是执行以下操作:

def equal_input(self, event): 
    self.display.icursor(END) 

ENDtkinter的参照结束的正规途径。这是tkinter内的一个变量,指向字符串'end'(因此,如果您喜欢,可以使用'end')。

Here is some more info on the Entry widget.

+1

什么是真正错从类(除了他应该用'RunGUI.equal_input',而不是'Calc.equal_input')以外的约束力? – fhdrsdg

+0

@fhdrsdg - 有趣。我从来没有见过这样做,但它的工作原理。尽管如此,我无法弄清楚如何将事件绑定到'Calc'实例中的特定窗口小部件。这是如何完成的? – TigerhawkT3

+1

好吧,'RunGUI'只是'Calc'的一个实例,所以通过'RunGUI'你可以访问'Calc'中'self'的任何东西。为了只绑定到这个特定'Calc'实例的入口控件,你可以简单地使用'RunGUI.display.bind('',RunGUI.equal_input)'。但是,如果您创建另一个'Calc'的实例,除非您专门添加它,否则它不会具有此绑定。 – fhdrsdg

1

嗯 - 你为什么要使用LEN?您可以使用icursor这样的:

self.display.icursor('end') 

也...这是我怎么绑定我的东西....

list_of_entrys = [entry_1, entry2] 

for entry in list_of_entrys: 
    entry.bind('<Return>', lambda event: self.something(event.widget)) 

(该event.widget部分表示在点击的来源)

...

此外,如果你想,你可以绑定到<Key>(所有按键) - 或者,如果它是一个屏幕键盘只是增加self.display.icursor('end')到打印的东西键...

用户按下任意键。密钥在传递给回调的事件对象的char成员中提供(这是特殊键的空字符串)。