0

我正在尝试制作一个接受用户输入并对其进行修改的程序(用户输入将是各种 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)
4

1 回答 1

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()'"

注意你的 repr 字符串中的 \n 。splitlines 将文本“分解”为 \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')
于 2019-10-26T09:26:53.557 回答