简体   繁体   中英

How to assign textvariable to different variable names within a loop - Python - Tkinter

Code:

for i in range(len(self.models_chosen)):
    self.test.insert(i, vars())
    self.model_entry_dict_text["entry" + str(i)] = ttk.Label(
        self.entry_frame,
        text="Quantity of: " + self.models_chosen[i]
    )
    self.model_entry_dict_text["entry" + str(i)].pack(fill=X)
    self.model_entry_dict["entry" + str(i)] = Spinbox(self.entry_frame, from_=0, to=2000,)
    self.model_entry_dict["entry" + str(i)].pack(fill=X)
    self.models_entry_box_created = True
    self.old_models = self.models_chosen

What I have done is made a dictionary within a for in range called -

self.model_entry_dict["entry" + str(i)]

So it would be:

self.model_entry_dict["entry1"] = Spinbox(self..) 
self.model_entry_dict["entry2"] = Spinbox(self..)
self.model_entry_dict["entry3"] = Spinbox(self..)  

...

depending on the range.

For each of the spinboxes that I have created, I need the value from inside them (which is why I have put the text variable option as part of the arguments) - The problem is I don't know how to have a different variable for each spinbox created due to the spinboxes being created in a loop.

Say I put self.textvariable , all the spinboxes would have the same value. An example of what I want to have would be

textvariable = self.variable+i

so:

self.variable1 to be the text variable for self.model_entry_dict["entry1"]  
self.variable2 to be the text variable for self.model_entry_dict["entry2"]
... etc.

To which I then just do:

self.variable1.get() - And it should get the number that is inside the spinbox

But I don't think it's possible to add a string/integer to a variable name.

Here you can see an image of the models I have chosen in the listbox, I then pressed update button and it generated 3 spinboxes, now I want to retrieve the numbers in the spinboxes (whether it be stored into 3 different variables or in a list/dictionary/array):

http://gyazo.com/a7c9847ec16b16fb443082066b42f890

example of what I'm looking for is (using the image provided above):

test1 = self.variable1.get()
print(test1)

    output:
        1800
test2 = self.variable2.get()
print(test2)

    output:
        300
test3 = self.variable3.get()
print(test3)

    output:
        30

I'm sorry if this may seem a little confusing, I started using Python for a week or so, so it's probably sloppy. I'm sure there's probably better ways of doing this and different methods.

You don't need to give each variable a name. Just use a list:

self.vars = []
for i in range(len(self.models_chosen)):
    var = StringVar()
    self.vars.append(var)
    ...
    self.model_entry_dict["entry" + str(i)].config(textvariable=var)

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