Search code examples
pythonfor-looptkintergettkinter-entry

How can I get input from multiple entry widgets created in a loop?


I've hunted through some of the previous answers and got a step closer, but my problem is still that I can not get the value from multiple entry boxes.

import tkinter as tk
from tkinter import ttk
window = tk.Tk()
my_list = []

def get_info():
    for each_player in my_list:
        tk.Label(window, text=temp_entry.get()).grid()

#number of players is determined by the user.
#In this example, lets say there are 3 players
tk.Label(window, text="Number of Players: ").grid()
num_of_players = ttk.Combobox(window, values=[1, 2, 3])
num_of_players.current(2)
num_of_players.grid(row=0, column=1)
#The code above is only the recreate the user selecting the amount of players from a combobox


#create number of entry boxes for user-determined number of players
for each_player in range(1, int(num_of_players.get()) + 1):
    temp_label = tk.Label(window, text="Player {}: ".format(each_player))
    temp_entry = tk.Entry(window)
    my_list.append(temp_entry)

    temp_label.grid(row=each_player, column=0, pady=10)
    temp_entry.grid(row=each_player, column=1, pady=10)
button = tk.Button(window, text="Save", command=get_info)
button.grid()

window.mainloop()

It's at the end of the code where I struggle to find out how I could possibly get information from the entry boxes. How can I use the get() method but only after the user has input text?


Solution

  • Your list contains entry widgets, so in your loop you need to reference the loop variable rather than temp_entry:

    def get_info():
        for each_player in my_list:
            print(each_player.get())