How to return a list from an event function in tkinter?
Here's something that illustrates what can be done since there's no meaningful way to return a value from an tkinter
event handler function. It shows how to reference a global variable like current_list
for use inside a function (i.e. by declaring it a global
).
You only need to do that when the function tries to change the value — the statement tells Python not to create a local variable with that name when something is assigned to it (which is the default behavior).
I've added a Process current list Button
to the GUI that will call a function which also added named process_list()
whenever it's clicked. This function contains the (commented-out) code you mentioned in one of your comments to indicate where processing like that could be done.
from tkinter import *from tkinter import ttkmy_window = Tk()my_frame_in = Frame(my_window)my_frame_in.grid(row=0, column=0)my_frame_out = Frame(my_window)my_frame_out.grid(row=0, column=1)listbox_events = Listbox(my_frame_in, height='5')listbox_events.grid(row=0, column=0, padx=10, pady=10)listbox_events_filtered = Listbox(my_frame_out, height='5')listbox_events_filtered.grid(row=0, column=2, padx=(0, 10), pady=10)my_instructions = Label(my_window, text='Use arrow keys to move selected items')my_instructions.grid(row=1, column=0, columnspan=3, pady=(0, 10))my_list_events = ['A', 'B', 'C', 'D']current_list = [] # Initilize global variable.for item in my_list_events: listbox_events.insert(END, item)def select_events(event=None): global current_list listbox_events_filtered.insert(END, listbox_events.get(ANCHOR)) listbox_events.delete(ANCHOR) current_list = list(listbox_events_filtered.get(0, END))def deselect_events(event=None): global current_list listbox_events.insert(END, listbox_events_filtered.get(ANCHOR)) listbox_events_filtered.delete(ANCHOR) current_list = list(listbox_events_filtered.get(0, END))def process_list(): print('current_list:', current_list)# for item in current_list:# x, y = np.loadtxt(item + '_' + 'Test.csv', skiprows=1, usecols=[my_col_x_axis,# my_col_y_axis], unpack=True, delimiter=',')my_button = Button(my_window, text='Process current list', command=process_list)my_button.grid(row=2, column=0, columnspan=3, pady=(0, 10))listbox_events.bind('<Right>', select_events)listbox_events_filtered.bind('<Left>', deselect_events)mainloop()