0

Intro: I am using the tkinter module to create two windows, each as separate classes. I want to take the integer entered on the first window, and use it to create that number of labels and entries in the second window.

i.e.

import tkinter

class FirstWindow:
    def __init__(self):
        self.firstMaster = tkinter.Tk()
        self.topFrame = tkinter.Frame(self.numberMaster)
        ...
        self.numEntry = tkinter.Entry(self.topFrame, width=10)
        ...
        self.averageButton = tkinter.Button(self.bottomFrame, text='next', command=self.nextstep)
        ...
        ...
        tkinter.mainloop()

    def nextStep(self):
        self.numberItems = int(self.numEntry.get())
        self.average = AveragerGUI(self.numberTests)

class AveragerGUI:
    def __init__(self, numTests):
        self.secondMaster = tkinter.Tk()
        self.topFrame = tkinter.Frame(self.secondMaster)

        for number in range(1, numTests):
            self.frame'number' = tkinter.Frame(self.secondMaster)

I know that this will not work; I included it just to illustrate what I want to do: create a number of frames dependent on the numTests parameter.

I thought of using a list, but this is a problem because I do not know how to convert the strings into the names of variables:

varList = []
for number in range(1, numberTests):
    label = str(number)
    var = 'Frame' + label
    varList.append(var)

Any thoughts?

2 Answers 2

1

If you use a list, there is no need to generate names:

self.frames = []
for number in range(numTests):
    self.frames.append(tkinter.Frame(self.secondMaster))

You can simplify that by using a list comprehension:

self.frames = [tkinter.Frame(self.secondMaster) for _ in in range(numTests)]

Now you can access each frame by index:

self.frames[0]
self.frames[1]

or loop through them:

for frame in self.frames:
    # do something with frame
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. If you are thinking about creating an arbitrary number of variables, you are almost always better served by a container of some sort, such a list or a dictionary.
0

Although I aggree with @Martijn Pieters, if you really did want to name variables inside a loop, the easiest way I have found to do this is to use the builtin exec function.

As an example, if I wanted to make x0, x1, x2, x3 equal the first 4 items of a list I would do the following:

>>>the_list = [1, 3.4, 'g', sum]

>>> for i in range(len(the_list)):
...    exec('x%i = the_list[%i]' % (i, i))

>>> print(x0)
1 
>>> print(x1)
3.4
>>> print(x2)
g
>>> print(x3)
<built-in function sum>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.