繁体   English   中英

如何更改输入框用户输入

[英]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))

暂无
暂无

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

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