Skip to main content
 首页 » 编程设计

python之更改光标在条目小部件中的位置

2025年05月04日13rubylouvre

我试图在按下按钮时将 Entry 小部件的光标向左移动。通过我的尝试,我可以获得光标的当前位置,但我无法移动它。
我在网上搜索,但没有找到任何有用的东西。如何移动 Entry 小部件中的光标位置?

#! /usr/bin/python 
from Tkinter import * 
 
class App(Frame): 
    def __init__(self,parent): 
        Frame.__init__(self,parent) 
        self.parent=parent 
        self.button = Button(self.parent, text="Shift_cursor_left", fg="red") 
        self.button.pack(side=LEFT) 
        self.entry_label=Entry(self.parent,width=10,bd="1",bg="cyan",font=("Helvetica",15),text="python",justify=RIGHT) 
        self.entry_label.pack() 
        self.entry_label.focus() 
        self.entry_label.insert(0,"Python") 
 
        self.button["command"]=self.shift_cursor() 
 
    def shift_cursor(self): 
        position = self.entry_label.index(INSERT) 
        print position 
        # self.entry_label.mark_set(INSERT,'1.2') 
 
root=Tk() 
app=App(root) 
root.mainloop() 

请您参考如下方法:

mark_set 是文本小部件的方法,对于条目小部件使用 icursor方法:

self.entry_label.icursor(0) 

另外,Button的命令应该是函数引用,而不是函数调用,所以改

self.button["command"]=self.shift_cursor() 

到

self.button["command"]=self.shift_cursor