'(Python TK) Get data entered into unnamed Entry widget
I've been working on a python program with a GUI created using Tkinter. I need to take user entry for a variable number of items, and then get the values entered by the user to use later in the program. Currently I've been doing this by iterating over a dictionary, and creating and adding a new Entry box for each key in the dictionary. The issue I've been having is, I'm not able to access those Entry boxes later on, since they aren't stored in an accessible variable.
This is a very basic example of the code I'm using (though in my code, instead of lists like sample_list, I'm importing dictionaries from a separate file that have different numbers of key-value pairs):
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
frame = ttk.Frame(root)
frame.grid(row=0, column=0)
sample_list = ["item 1", "item 2", "item 3"]
row=0
for item in sample_list:
label = ttk.Label(frame, text=item)
label.grid(row=row, column=0)
entry = ttk.Entry(frame)
entry.grid(row=row, column=1)
row += 1
root.mainloop()
What I'm trying to do is access the entry boxes created in the for statement later on. Since they aren't assigned to a variable that's accessible outside the loop, I haven't been able to figure out how to access them. I've tried something like this (as a function assigned to a button press):
input_list = []
for widget in frame.winfo_children():
if widget.winfo_class == "Entry":
input_list.append(widget.get())
else:
pass
But Tkinter doesn't seem able to call the .get() method if it's accessing all of the widgets in a frame. When I've used print to check the contents of the input_list, it comes up as an empty list ([]). Is there any way to access the value of these entry boxes from outside the for loop?
Solution 1:[1]
Simply keep entries on list, instead of single variable
all_entries = []
for item in sample_list:
# ... code ...
entry = ttk.Entry(frame)
# ... code ...
all_entries.append( entry )
And later you can get values using this list
all_inputs = []
for entry in all_entries:
all_inputs.append(entry.get())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | furas |
