tinker Form question(s)
Peter Otten
__peter__ at web.de
Mon Sep 7 09:08:44 EDT 2020
Steve wrote:
> I am not sure how to post the code for my file here, is copy/paste the
> best way?
Yes. Try to paste only the relevant parts, or, if possible, post a small
self-contained example that can be run by the reader without further
editing.
> Is there another? I understand that attachments are stripped
> off.
>
> """
> The following segment of code returns values of "spec".
> I would like to have it return the associated value of
> "DataLine" with each spec. It would also be nice to understand
> how this code works to hold/return the information.
>
> In pseudocode, a line something like:
>
> DataReturned = DataLine + " " + spec)
> New_Specs.append(DataReturned)
>
> explains what I would like to have returned.
> return ([spec.get()for spec in New_Specs])
[spec.get() for spec in New_Specs]
is called "list comprehension" and is syntactic sugar for a list-creating
loop like
result = []
for spec in New_Specs:
result.append(spec.get())
The relevant parts of the loop where you set up the GUI and the New_Specs
list:
> New_Specs = []
> for lineItem in range(len(ThisList)):
> DataLine, Spec = GetLineByItem(ThisList[y])
...
> NewSpec = tk.StringVar()
> New_Specs.append(NewSpec)
First, using range(len(ThisList)) is almost always superfluous as you can
iterate over the list directly. In your case:
> New_Specs = []
for item in ThisList:
> DataLine, Spec = GetLineByItem(item)
...
> NewSpec = tk.StringVar()
> New_Specs.append(NewSpec)
Now, as you need DataLine later-on why not keep a copy? So let's turn
New_Specs into a list of StringVar, DataLine tuples:
> New_Specs = []
for item in ThisList:
> DataLine, Spec = GetLineByItem(item)
...
> NewSpec = tk.StringVar()
New_Specs.append((NewSpec, DataLine))
When the function terminates (there is a mainloop() missing) you can create
and return the result:
# long form, with a loop
result = []
for spec, dataline in New_Specs:
result.append(dataline + " " + spec.get())
return result
# alternative using a listcomp:
return [dataline + " " + spec.get() for spec, dataline in New_specs]
More information about the Python-list
mailing list