简体   繁体   English

在python 3中的Tkinter条目小部件中删除光标左侧的字符

[英]Remove a character on the left of the cursor in Tkinter entry widget in python 3

I want to make a program in which when I click a button it clears a character left to the cursor from the entry widget.我想制作一个程序,当我单击一个按钮时,它会从条目小部件中清除光标左侧的一个字符。

here is what I tried:这是我尝试过的:

import tkinter as tk


def clear_one(entry_field):
    from tkinter import END
    current = entry_field.get()
    current = str(current)
    cleared = current[:-1]
    entry_field.delete(0, END)
    entry_field.insert(0, cleared)


root = tk.Tk
e = tk.Entry()
e.grid(row=0, column=0)
e.focus()

b = tk.Button(text="Clear", command=lambda: clear_one(e))
b.grid(row=1, column=0)

tk.mainloop()

It just deletes the last character in the entry widget and when I move the cursor to another position and click the button it still deletes the last character in the entry widget.它只是删除条目小部件中的最后一个字符,当我将光标移动到另一个位置并单击按钮时,它仍会删除条目小部件中的最后一个字符。

But I want it to delete the character left to the cursor.但我希望它删除光标左侧的字符。

I did not find any proper solution online and it might be possible that I was unable to understand those as I'm new to programming.我没有在网上找到任何合适的解决方案,我可能无法理解这些,因为我是编程新手。

Can anyone help me with this?谁能帮我这个?

If you want to delete the character to the left of the cursor, determine the position of the cursor, subtract one, then delete that character.如果要删除光标左侧的字符,请确定光标的位置,减一,然后删除该字符。

def clear_one(entry_field):
    insert = entry_field.index("insert")
    entry_field.delete(insert-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM