tkinter radiobutton
William Gill
noreply at gcgroup.net
Wed Jun 29 10:04:45 EDT 2005
I did some more digging based on your code, and discovered list
comprehensions. They didn't register the first time I skimmed the
language reference and tutorial. It's obvious the more I learn, the
more I need to relearn what I think I know. I need to study
comprehensions, but they open up lots of opportunities for simpler,
clearer code.
>> return row == var.get()
Oops! I saw this as soon as I sent it, but knew you would get my point.
> var.set(-1)
Though both ways may seem roughly equivalent today, I'd bet that in 6
months
...
var.set(-1) # initialize as no choice
...
will be clearer.
Thanks again!
Bill
Peter Otten wrote:
> William Gill wrote:
>
>
>>Also, does 'row == var.get() for var in self.variables' perform the
>>comparison row == var.get() for each item in self.variables? I would
>>have had to write:
>>
>>for var in self.variables:
>> return row == var.get()
>
>
> Or rather
>
> result = []
> for var in self.variables:
> result.append(row == var.get())
> return tuple(result)
>
> This can be rewritten to a 'list comprehension'
>
> return tuple([row == var.get() for var in self.variables])
>
> and, since Python 2.4, to the 'generator expression' that I used and which
> avoids building the intermediate list. Both constructs also feature an
> if-clause, see
>
> http://docs.python.org/tut/node7.html#SECTION007140000000000000000
> http://docs.python.org/tut/node11.html#SECTION00111100000000000000000
>
>
>>p.s. I tweaked
>>
>>rbn = tk.Radiobutton(self, text=text, variable=var, value=y)
>>to
>>rbn = tk.Radiobutton(self, text=text, variable=var, value=y+1)
>>
>>and
>>
>>return tuple(row == var.get() for var in self.variables)
>>to
>>return tuple(row+1 == var.get() for var in self.variables)
>>
>>so that the Radiogrid doesn't initialize w/row 1 selected, and
>>accomodates cases where nothing is selected in any column.
>
>
> Another option would have been to initialize the variables
>
> ...
> var = tk.IntVar()
> var.set(-1)
> if trace_write:
> ...
>
> Peter
>
More information about the Python-list
mailing list