Search code examples
python-3.xtkintertk-toolkitsimpledialog

Creating a simpledialog with tk that has a variable number of inputs and then outputting them


Im trying to create a simpledialog box in which you can input numbers. The number of inputs however does depend on a dataset, technically people are using it to input rows into a dataset.

I cannot figure out how to get it to work.

Ive tried putting the 'e1' objects into a dictionary and then later using them however this gives an unknown option error

class MyDialog(simpledialog.Dialog):
def body(self, master):
    d2={}
    f={}
    for i in range(len(df_data_1.columns) -1 ):
        Label(master, text=df_data_1.columns[i]).grid(row=i)
        self.e1 = Entry(master)
        self.e1.grid(row=i, column=1)
        d2[df_data_1.columns[i]] = self.e1.get()

        print(d2[df_data_1.columns[i]])
    return self.e1
    print(self.e1)
    f[df_data_1.columns[i]]=self.e1
    return d2 # initial focus
    return f
    print(f)

def apply(f):
    for x in range(len(df_data_1.columns) -1 ):
        d2[df_data_1.columns[x]] = f[df_data_1.columns[x]].get()
        print(d2[df_data_1.columns[x]])
    first = d2
    print(first)

root = Tk()
d = MyDialog(root)
print (d.result)  

Solution

  • You need to store the instances in a list. The problem with your code is that you overwrite self.e1 on every iteration of the loop.

    It would look something like this (untested, since you didn't give us code we can run to duplicate the problem):

    self.entries = []
    for i in range(len(df_data_1.columns) -1 ):
        Label(master, text=df_data_1.columns[i]).grid(row=i)
        entry = Entry(master)
        entry.grid(row=i, column=1)
        self.entries.append(entry)
    

    You can later iterate over all of the entries like this:

    for entry in self.entries:
        value = entry.get()
        print("value:", value)