Victor Pira
Victor Pira

Reputation: 1172

Creating and using widgets (Scale) in Tkinter using for-loop

I am currently facing the problem of creating many (over 20) scales in Tkinter and naturally I am trying not to create and use them "manually".
Creating works just fine:

for ii in range(0,25):
  nam='input_a' + str(ii)
  nam = Scale(master, from_=100, to=0, orient=VERTICAL)
  nam.grid(row=0, column=2+ii)

Problem occurs when I am trying to get the values:

import numpy as np

def Aux():
  a=np.zeros(25)
  for ii in range(0,25):
    nam='input_a'+str(ii)
    a[ii]=nam.get()
  return a

The problem: nam is still a str-object, therefore it couldn't have an attribute get.

Any hints? Thanks!

Upvotes: 0

Views: 308

Answers (2)

Bryan Oakley
Bryan Oakley

Reputation: 385900

I find that a dictionary is very convenient for storing widgets, though a list will do just as nicely if you only want to access them by an integer index:

scales = {}
for ii in range(0,25):
    scales[ii] = Scale(...)

Upvotes: 1

fhdrsdg
fhdrsdg

Reputation: 10532

Save the references to your Scales in a list

nam = []
for ii in range(0,25):
  nam.append(Scale(master, from_=100, to=0, orient=VERTICAL))
  nam[-1].grid(row=0, column=2+ii)

You can then use nam[ii].get()

Upvotes: 1

Related Questions