Tkinter-Text:使文本框将多行识别为单独的输入吗?

时间:2019-10-26 09:20:44

标签: python tkinter tkinter-text

我正在尝试制作一个接受用户输入并对其进行修改的程序(用户输入将是各种10位数的数字字符串),然后返回修改后的结果。目前,我可以通过单行输入实现我想要的功能,但是我想添加功能,以允许用户输入多个输入,并让程序分别修改每个输入。但是,在当前状态下,尽管位于单独的行中,它仍将简单地修改文本框中的所有内容,就好像它是一个长字符串一样。

我当时想我可以尝试将文本框中的每个输入都变成一个列表,然后以这种方式进行迭代?我不确定是否有更好的方法可以做到这一点?

import tkinter as tk

root = tk.Tk()

def returnEntry(arg=None):

    rawresult = myEntry.get("1.0","end-1c")

    #functionality here
    modifiedresult = rawresult+str(' modded')

    resultLabel.config(text=modifiedresult)
    myEntry.delete(0,END)

canv = tk.Canvas(root,height=500,width=1000,bg='misty rose')
canv.pack()

myEntry = tk.Text(root, width=60)
myEntry.focus()
myEntry.bind("<Return>",returnEntry)
myEntry.place(relx=.05,rely=.1)

enterEntry = tk.Button(root, text= "Convert", command=returnEntry, bg='snow')
enterEntry.pack()

resultLabel = tk.Label(root, text = "")
resultLabel.place(relx=.55,rely=.1)

root.geometry("+700+400")

root.mainloop()

当前它仅修改文本框中的所有内容,就好像它是一个长字符串一样。

更新的代码:

def returnEntry(arg=None):

    rawresult = myEntry.get("1.0","end-1c")

    list_of_entries = []

    for line in rawresult.splitlines():
        list_of_entries.append(line.upper())
#--------------------------------------------------------------
            #functionality here
        for entries in list_of_entries:
            modifiedresult = entries+str(' modded')
#--------------------------------------------------------------
            resultLabel.config(text=modifiedresult)
            myEntry.delete(0,END)

1 个答案:

答案 0 :(得分:0)

只需使用str.splitlines()即可处理:https://www.tutorialspoint.com/python/string_splitlines.htm

my_text = """This is a very lenghty text example
To give an idea on operating
On strings using built-in method
string.splitlines()"""

repr(my_text)

"'This is a very lenghty text example\\nTo give an idea on operating\\nOn strings using built-in method\\nstring.splitlines()'"

注意您的代表​​字符串中的\ n。分隔线将文字“分解”为\ n(换行符)之间的片段。

## just print
for line in my_text.splitlines():
    print(line+'\n')

## do some transormation
for line in my_text.splitlines():
    print(line.lower()+'\n')

## append to a list to do some further transformation
some_list = []
for line in my_text.splitlines():
    some_list.append(line.upper())
print(some_list[-1]+'\n')