Problem running a FOR loop

Peter Otten __peter__ at web.de
Sun Aug 30 05:29:05 EDT 2020


Steve wrote:

> Compiles, no syntax errors however, line 82 seems to run only once when
> the FOR loop has completed.
> Why is that?  All fields are to contain the specifications, not just the
> last one.

It seems that passing the StringVar to the Entry widget is not sufficient to 
keep it alive.

>     for lineItem in range(len(ThisList)):

>          NewSpec = tk.StringVar()
>          SVRCodeEntered = ttk.Entry(window, width = 15, textvariable =
> NewSpec)

When the previous NewSpec is overwritten with the current one the previous 
gets garbage-collected and its value is lost. 

The straight-forward fix is to introduce a list:

      new_specs = []
>     for lineItem in range(len(ThisList)):

>          NewSpec = tk.StringVar()
           new_specs.append(NewSpec)
>          SVRCodeEntered = ttk.Entry(window, width = 15, textvariable =
> NewSpec)

Another option is to store the StringVar as an attribute of the Entry:

>     for lineItem in range(len(ThisList)):

>          NewSpec = tk.StringVar()
>          SVRCodeEntered = ttk.Entry(window, width = 15, textvariable =
> NewSpec)
           SVRCodeEntered.new_spec = NewSpec




More information about the Python-list mailing list