因此,在我正在编码的程序中,我将键盘上的 Enter 键绑定(bind)到一个函数。在此函数中,光标应移动到条目小部件中文本的末尾。因此,例如,如果用户在输入小部件中有 122|57(| 是光标),那么当按下 Enter 时,我希望该光标移动到末尾以给出 12257|。我尝试实现这一目标导致了错误。下面是我正在使用的代码:
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: 'Event' object has no attribute 'display'”
任何帮助将不胜感激。谢谢
最佳答案
您应该在应用程序本身内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)
END
是 tkinter
表示结束的规范方式。它是 tkinter
中的一个变量,指向字符串 'end'
(因此,如果您愿意,可以使用 'end'
代替)。
关于Python - 在 Tkinter 中使用绑定(bind)键移动输入光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30499545/