pythonuser-interfacetkintercomboboxtkinter-scrolledtext

populate scrolled text window with Combobox value (python)


I'm trying to build a GUI in Python where a scrolled text window is populated with one or more values selected from a Combobox.

e.g if the values in the Combobox are 1, 2, 3, 4. if I click 1 it appears in the scrolled text window, then if I clicked 2 that is also added to the scrolled text window without erasing the previous selection.

Can anyone help? Below is the code I have so far.

#Library imports
from tkinter import *
from tkinter.ttk import *
from tkinter import scrolledtext

#window geometry
window = Tk()
window.geometry('180x220')
window.title('DFC Selector')

#Window Text
lbl = Label(window, text = "Select DFC", font = ("Arialbold",11))
lbl.grid(column=0, row=0)

# Read values from file
fcode = []
with open('DFCs.txt') as inFile:
    fcode = [line for line in inFile]
    fcode = sorted(fcode)

#Combo box
combo = Combobox(window,width=25)
combo['values']= (fcode)
combo.current(1) 
combo.grid(column=0, row=2)

#Text window
txt = scrolledtext.ScrolledText(window,command=clicked,width=20,height=10)
txt.grid(pady=15,padx=10,column=0,row=3)

#Fault code selection to text window
def clicked():
    txt.configure(text=combo.get)

#Start GUI
window.mainloop()

Solution

  • use txt.insert() to insert text into Text and use end as a parameter to insert at the end

    from tkinter import *
    from tkinter.ttk import *
    from tkinter import scrolledtext
    
    
    def clicked(event):
        txt.insert("end", var.get()+'\n')
    
    #window geometry
    window = Tk()
    window.geometry('180x220')
    window.title('DFC Selector')
    
    #Window Text
    lbl = Label(window, text = "Select DFC", font = ("Arialbold",11))
    lbl.pack()
    
    # Read values from file
    fcode = ['Hello', 'Random', 'BSAE']
    
    var = StringVar()
    #var.trace('w', insert)
    
    #Combo box
    combo = Combobox(window,width=25, textvariable=var, state="readonly")
    combo.bind("<<ComboboxSelected>>", clicked)
    combo['values']= (fcode)
    combo.current(1) 
    combo.pack()
    
    #Text window
    txt = scrolledtext.ScrolledText(window,width=20,height=10)
    txt.pack()
    
    #Fault code selection to text window
    
    
    #Start GUI
    window.mainloop()