Change the position of cursor in Tkinter’s Entry widget
A widget in tkinter, which is used to enter a display a single line of text is called an entry widget. Have you created an entry widget in tkinter which contains a lot of information? Is a lot of text causing an issue to you to move at any other position in it? Don’t worry, we have a solution to this problem. What you need to do is to just set a button which when clicked will take you to the desired location in the entry widget.
Steps Needed:
Step 1: First, import the library tkinter.
from tkinter import *
Step 2: Now, create a GUI app using tkinter.
app = Tk()
Step 3: Then, create a function with an argument as None to move the cursor wherever you want in the entry widget.
def shift_cursor(event=None):
position = entry_label.index(INSERT)
entry_label.icursor(#Specify the position \
where you want to move the cursor)
Step 4: Next, create and display an entry widget in which you want to change the position.
entry_label=Entry(app)
entry_label.grid(column=#Specify the column value,
row=#Specify the row value,
padx=#Specify the padding value of x,
pady=#Specify the padding value of y)
Step 5: Once an entry widget is declared, set the focus to the entry widget specified.
entry_label.focus()
Step 6: Further, create and display a button which when clicked will change the position of the cursor in the entry widget.
button1 = Button(app,
text="#Text you want to display in button",
command=shift_cursor)
button1.grid(column=#Specify the column value,
row=#Specify the row value,
padx=#Specify the padding value of x,
pady=#Specify the padding value of y)
Step 7: Finally, make an infinite loop for displaying the app on the screen.
app.mainloop()
Example:
In this program, we will change the position of the cursor one character left by clicking on the button ‘Shift cursor left‘ while changing the position of the cursor one character right by clicking on the button ‘Shift cursor right.’
Python
from tkinter import *
app = Tk()
def shift_cursor1(event = None ):
position = entry_label.index(INSERT)
entry_label.icursor(position - 1 )
def shift_cursor2(event = None ):
position = entry_label.index(INSERT)
entry_label.icursor(position + 1 )
button1 = Button(app, text = "Shift cursor left" , command = shift_cursor1)
button1.grid(row = 1 , column = 1 , padx = 10 , pady = 10 )
button2 = Button(app, text = "Shift cursor right" , command = shift_cursor2)
button2.grid(row = 1 , column = 0 , padx = 10 , pady = 10 )
entry_label = Entry(app)
entry_label.grid(row = 0 , column = 0 , padx = 10 , pady = 10 )
entry_label.focus()
app.mainloop()
|
Output:
Last Updated :
05 Apr, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...