Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

user interface - 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()
question from:https://stackoverflow.com/questions/66060442/populate-scrolled-text-window-with-combobox-value-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...