Search code examples
pythontkintertkinter-text

Tkinter-Text: Make text box recognize multiple lines as separate inputs?


I am trying to make a program that takes user input and modifies it (the user input will be various 10-ish digit strings), then returns the modified result. I can currently achieve what I want with a single line of input, but I would like to add the functionality to allow the user to enter multiple inputs, and having the program modify each input separately. However, in its current state it will simply modify everything in the text box as if it were one long string, despite being on separate lines.

I was thinking I could try to make each input in the text box into a list, and iterate through it that way? I'm not sure if there is a better way to do this?

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

It currently only modifies everything in the textbox as if it were one long string.

UPDATED CODE:

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)

Solution

  • Just use str.splitlines() to handle it: 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()'"
    

    ​ Notice \n in your repr string. splitlines 'breaks' the text down into slices betwen \n (newline).

    ## 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')