我第一次在python中使用Tkinter。 我试图让用户输入的输出为小写。 因此,如果输入“TEST”,则输出为“TEST”
我的代码是:
from tkinter import *
# event functions (10:30 mins)
def onClickSubmitButton(): # submit button event handler
userEnteredText = textbox.get() # get the enterd text from the Entry text box
outputTextField.delete(0.0, END) # (14:30 mins)delete all of the output field text contents
outputTextField.insert(END, userEnteredText) # (15:50 mins) output the user eneterd text
#main window (1:30 mins)
window = Tk()
window.title("Python Glossary")
window.configure(background="white")
# display text using - Label (05:30 mins)
Label(window, text="Enter a string and press submit", bg="white", font="none 12 bold").grid(row=1,column=0,sticky=W) # using grid layout
# textbox for text entry - Entry (8:15 mins)
textbox = Entry(window, width=20, bg="white")
textbox.grid(row=2, column=0,sticky=W) # grid position of textbox
# submit button - Button (9:30 mins) - calls onClickSubmitButton function when clicked
Button(window, text="SUBMIT", width=6, command=onClickSubmitButton ).grid (row=2,column=1, sticky =W)
#definitions - Label (11:50 mins)
Label(window, text="\n Your string", bg="white", font="none 12 bold").grid(row=4,column=0,sticky=W) # using grid layout
# output textField - Text(12:40 mins)
outputTextField = Text(window, width=75, height=6, wrap=WORD, background="white",)
outputTextField.grid(row=4, column=1,sticky=W) # grid position of textField
# run the main loop
window.mainloop()
我试过:
outputTextField.insert.lower(END, userEnteredText)
但那没用。有什么建议吗
如果执行
outputTextField.insert(END, userEnteredText.lower())
,则输入的文本将转换为小写,然后插入函数按预期工作,以小写字符串作为参数因此,这里有一个更为奇特的选项(我不知道您是否需要类似的功能,但它也能满足您的要求,只是不必按下按钮将字符更改为小写,在这种情况下,它会在用户键入时执行此操作,请尝试):
基本上,它只是将
"<Key>"
事件绑定到文本小部件,这意味着当按下任何键时(焦点在文本小部件上),将触发事件,然后调用给定的函数。此外.bind
还传递一个事件参数,以便即使不使用也应处理该参数,但在这里,它用于检测字符或在按下的键没有字符时停止函数(例如,“Caps Lock”或“Backspace”(实际上有字节类型thingy,这就是为什么还有r"\x" in repr(event.char)
的其他比较)。然后,它只是删除刚写的字符,并在其位置放置一个小写的新字符。之所以使用root.after
,是因为在向文本小部件键入字符之前调用了事件,这意味着使用了不正确的索引,因此会有一个微小的延迟(1毫秒),以便字符可以出现在屏幕上,然后进行索引编辑:也可以向if语句添加
or event.char.islower()
(如果不起作用,也可以尝试or not event.char.isupper()
),以稍微提高性能,因为如果字符已经是小写的,它将不会经过替换过程编辑2:根据PEP8,您应该使用
snake_case
来命名变量和函数,而不是camelCase
有用的资料/文件:
在这些字符串方法的大多数情况下,您需要知道 为它创建一个新变量
相关问题 更多 >
编程相关推荐