简体   繁体   中英

Get The Inputs from a list created with a for loop and store them as a tuple

I have an issue, when I create a list of entries generated by a "for loop". on each loop, two entries get generated. my purpose is when The user clicks the "create" button -> get the data from the entries and store it inside a list as tuples "(arc, capacity)".

This Is My Code :

    inputs = []
    def show_inputs():

        for input in inputs:
            label.config(text=f'{input}\n')

    edges_number = edges_variable.get()
    if is_weighted_variable.get():
        for i in range(edges_number):
            edge_name_label = tk.Label(second_frame, text=f'Arc {i + 1}')
            edge_weight_label = tk.Label(second_frame, text=f'Capacité {i + 1}')
            edge_name_label.grid(row=i + 1, column=i - i)
            edge_weight_label.grid(row=i + 1, column=i + 2 - i)
            edge_name_entry = tk.Entry(second_frame, )
            edge_weight_entry = tk.Entry(second_frame)
            edge_name_entry.grid(row=i + 1, column=i - (i - 1))
            edge_weight_entry.grid(row=i + 1, column=i + 3 - (i - 1))
            inputs.append((edge_name_entry.get(), edge_weight_entry.get()))
    else:
        for i in range(edges_number):
            edge_name_label = tk.Label(second_frame, text=f'Arc {i}')
            edge_name_label.grid(row=i + 1, column=i - i)
            edge_name_entry = tk.Entry(second_frame, )
            edge_name_entry.grid(row=i + 1, column=i - (i - 1))
            inputs.append(edge_name_entry.get())

    show_inputs_button = tk.Button(second_frame, text="Creer", command=show_inputs)
    show_inputs_button.grid(columnspan=2)

在此处输入图像描述

You need to save the widgets in the list, not the result of the .get() method.

for i in range(edges_number):
    ...
    inputs.append(edge_name_entry)

Later, you can iterate over the list to get the current values:

for input in inputs:
    print(input.get())

Or, you can use a list comprehension to return a list of values:

values = [input.get() for input in inputs]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM