Python使用绑定键在Tkin中移动条目光标

2024-09-30 01:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

所以在一个程序中,我把键盘上的enter键绑定到一个函数上。在这个函数中,光标应该移动到entry小部件中文本的末尾。例如,如果用户在entry小部件中有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()

当我按enter键时遇到一个错误,该键显示“AttributeError:'Event'object has no attribute'display'”

任何帮助都将不胜感激。谢谢


Tags: 函数self部件def错误displaycalcroot
2条回答

你为什么要用莱恩?你这样使用icursor:

self.display.icursor('end')

还有。。。我就是这样绑东西的。。。。在

^{pr2}$

(在事件控件部分说明点击的来源)

。。。在

另外,如果你想的话,你可以绑定到<Key>(所有按键)-或者如果是屏幕键盘,只需在打印按键的东西上添加self.display.icursor('end')。。。在

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

您应该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()函数来执行以下操作:

^{pr2}$

ENDtkinter表示结尾的规范方式。它是tkinter内的一个变量,它指向字符串'end'(因此,如果您喜欢,可以使用'end')。在

{a1}

相关问题 更多 >

    热门问题