freakrho
freakrho

Reputation: 555

Python Tkinter - Place several entries within a for

I have a code that displays several entries and the number of entries depends on a previous entry, the problem is that I can't have the entries to be independent.
Here is my code (it's just the part of the problem), with this code the chosen amount of entries appear, but when you type in one all the entries get edited.

#The variable amCon is acquired previously
for r in range(amCon):
    cant_entry = ttk.Entry(mainframe, textvariable=names)
    cant_entry.grid(column=0, row=r+1, sticky='WE')

I want to be able to have each entry to be part of a list so I can use them separately.

Upvotes: 0

Views: 1493

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385980

You are assigning the same variable to all of the entry widgets. You need to either create a separate variable for each, or just don't use the textvariable1 option. That option isn't necessary -- you can still get and set the contents of the widget using methods on the widget itself. The textvariable is mainly for convenience (and because it's sometimes nice to put a trace on the variable so you know when it changes).

Here's a contrived example that has 5 entries, an a sixth entry that shows the value of the other five as a list:

import tkinter as tk
import ttk

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.size=5
        self.vars = {}
        for i in range(self.size):
            self.vars[i] = tk.StringVar()
            entry = ttk.Entry(self, textvariable=self.vars[i])
            entry.pack(side="top", fill="x")
            self.vars[i].trace("w", self.callback)

        # this entry will show the other values as a list
        self.e0Var = tk.StringVar()
        self.e0 = ttk.Entry(self, textvariable=self.e0Var)
        self.e0.pack(side="top", fill="x", pady=(4,0))

        # call the callback once to establish the initial value
        self.callback()

    def callback(self, *args):
        values = []
        for i in range(self.size):
            values.append(self.vars[i].get())
        # make a comma separated list and store in e0Var
        self.e0Var.set(str(values))

app = App()
app.mainloop()

Upvotes: 0

user1122107
user1122107

Reputation: 73

I believe you want to have another variable than cant_entry. Try a list!

entries = []
entries.append(ttk.Entry(mainframe, textvariable=names))
entries[0]

You see, when you are placing different stuff under the same name (cant_entry) then they will all appear, but they are all linked to cant_entry. When you edit one cant_entry, all the others get edited too. The list is much more dynamic and you can use the append function to place elements in a list. Then use entries[number of entry] to get what you put in.

Upvotes: 1

Related Questions