我在优秀的Tkdocs网站上使用的一个例子是谈论复选框,我想修改它以显示检查了哪些复选框(在标签中)。
我定义了一个函数,然后重新认为第二个更清晰 因此更加pythonic。
但是我确信还有更好的方法......
如果不明显的是onevar twovar和threevar是复选框,那么outvar就是我在标签中显示的变量......
欢迎评论!
def checkvars(*args):
if onevar.get():
if twovar.get():
if threevar.get():
outvar.set('All three are true')
else:
outvar.set('one and two are set to true')
elif threevar.get():
outvar.set('one and three are set to true')
else:
outvar.set('one is set to true')
elif twovar.get():
if threevar.get():
outvar.set('two and three are set to true')
else:
outvar.set('two is set to true')
elif threevar.get():
outvar.set('three is set to true')
else:
outvar.set('They are all false')
def checkvars2(*args):
if onevar.get() and twovar.get() and threevar.get():
outvar.set('All three are true')
elif onevar.get() and twovar.get():
outvar.set('one and two are set to true')
elif onevar.get() and threevar.get():
outvar.set('one and three are set to true')
elif onevar.get():
outvar.set('one is set to true')
elif twovar.get() and threevar.get():
outvar.set('two and three are set to true')
elif twovar.get():
outvar.set('two is set to true')
elif threevar.get():
outvar.set('three is set to true')
else:
outvar.set('They are all false')
答案 0 :(得分:1)
怎么样的东西: 这并不比你所拥有的要短很多,但是如果你得到更多的'vars'那么这会更好地扩展
def checkvars(*args):
numbers = ['one', 'two', 'three']
flags = [x.get() for x in (onevar, twovar, threevar)]
numbers = filter(flags, numbers)
if len(numbers) == 0:
outvar.set('They are all false')
elif len(numbers) == len(numbers):
outvar.set('All three are true')
else:
is_are = {1 : 'is'}.get(l, 'are')
comma_list = ''.join(('%s, ' % x for x in numbers[:-2]))
and_list = ' and '.join(numbers[-2:])
outvar.set(%s%s %s set to true' % (comma_list, and_list, is_are))
将最后一个更改为','当数字中有3个或更多时将其分开
答案 1 :(得分:1)
azorius的小变化回答完整性:
def checkvars(*args):
flags = [x.get() for x in (onevar, twovar, threevar)]
# Generate a list containing the corresponding string representation of
# each checked flag value.
# For example: (True, False, True) gives ('one', 'three')
num_strings = ('one', 'two', 'three')
val_strings = [s for f, s in zip(flags, num_strings) if f]
# Number of checked values correspond to the number of strings.
checked_count = len(val_strings)
if checked_count == 0:
outvar.set('They are all false')
elif checked_count == len(flags):
outvar.set('All three are true')
else:
verb = 'is' if len(val_strings) == 1 else 'are'
outvar.set('%s %s set to true' % (' and '.join(val_strings), verb))
无论语言如何,很多if
/ elif
的函数都很少被接受。