简体   繁体   中英

How do I collect multiple entries into a single label using tkinter?

I'm trying to create a tkinter program that allows for dynamically adding Entry fields using a button. I have that in place but now I am trying to store the user inputs as variables for however many entry boxes are added. Ideas?

For example if I hit the button 4 times and 4 Entry boxes are added I want to store those 4 user entries as 4 variables (or at least strings) for further use

Current code:

# add() adds multiple text boxes

all_unq = []
count = 0
def add():
    global count
    MAX_NUM = 15
    if count <= MAX_NUM:
        all_unq.append(tk.Entry(main)) # Create and append to list
        all_unq[-1].grid(row=14+count,column=1,`enter code here`pady=5) 
# Place the just created widget
        count += 1 # Increase the count by 1

First, you'll need some initial variables...

import tkinter as tk

root = tk.Tk()
entries = []

createEntry = tk.Button(root, text="click me!")
createEntry.grid(column=0, row=0, pady=15)

Then, you will need a function to create the entry when the button is clicked...

def makeEntry():
    entry = tk.Entry(root)
    entry.grid(column=len(entries)+1, row=0, pady=3)

    entries.append(entry)

Finally, you wrap everything up by calling root.mainloop and binding the button to the mouse to make it responsive...

createEntry.bind("<Button-1>", command=makeEntry)
root.mainloop()

You have a list of entry widgets, just iterate over it. For example, here's how to print the value from each entry widget. Note that you'll need to declare all_unq as global if you want to do this in a separate function.

for entry in all_unq:
    print(entry.get())

If you want a list with all of the values, you can use a list comprehension:

all_values = [entry.get() for entry in all_unq]

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