如何更改输入框用户输入

How to change entry box user input

我希望能够将 撇号 (') 的用户输入更改为此 反引号符号 (`) 因为我使用用户输入向 MySQL 数据库询问用户要求的信息,并且 MySQL 字符串以撇号开头或结尾。这意味着如果用户输入一个并且 python 试图用它做任何事情,最终会出现错误所以我只想能够将 (') 更改为 (`)当用户将其键入输入框并在输入框中显示时,但我遇到了麻烦。我不想对 MySQL 数据库进行任何更改,所以我只想 python 自己解决这个问题。

from tkinter import *  # allows for the use of tkinter GUI

win = Tk()  # creates the tkinter window
win.title("test")  # sets the name of the window
win.geometry("300x200")  # sets the size of the window
win.resizable(False, False)  # prevents the window from being resized

def changeto(e):
    nsearchentry.insert(-1,'hi')
    print(nsearchentry)

nsearchentry = Entry(win, width=20, font=('Arial', 12))  # sets up the nsearch entry box and its parameters
nsearchentry.pack()  # moves the nsearchentry box to its location
nsearchentry.bind("'", changeto)

win.mainloop()

如果你想在内部转换(用户不会知道)那么最后(就在你想使用该数据之前)使用 .replace().
示例代码是:

data=nsearchentry.get()
data=data.replace("'","`")
#Here you want to use that data

或者如果你想要实时的,那么试试这个:

def ch():
    x=nsearchentry.get()
    nsearchentry.delete(0,END) 
    # We have to delete to make sure same text won't overwrite again
    nsearchentry.insert(0,x.replace("'","`"))

nsearchentry.bind("'", lambda e: win.after(1,ch)) 
# 1 Millisecond delay just to make sure that ' is written in Entry

绝招:

def ch():
    x=nsearchentry.get()
    nsearchentry.delete(0,END)
    nsearchentry.insert(0,x[0:-1]+"`")
    # Remove ' and add `

nsearchentry.bind("'", lambda e: win.after(1,ch))