如何使代码更紧凑?

时间:2018-01-06 11:22:11

标签: python python-3.x user-interface tkinter

你可以帮我把它变得更紧凑吗?我需要这样做,以便对于每个值[0]我得到另一张图片。我的脚本有效,但我发现它太长而且太笨重。

if board[0] == 0 :
    square_1_button.config(image=T0S)
if board[0] == 1 :
    square_1_button.config(image=T1S)
if board[0] == 2 :
    square_1_button.config(image=T2S)
if board[0] == 3 :
    square_1_button.config(image=T3S)
if board[0] == 4 :
    square_1_button.config(image=T4S)
if board[0] == 5 :
    square_1_button.config(image=T5S)
if board[0] == 6 :
    square_1_button.config(image=T6S)
if board[0] == 7 :
    square_1_button.config(image=T7S)
if board[0] == 8 :
    square_1_button.config(image=T8S)
if board[0] == 9 :
    square_1_button.config(image=T9S)
if board[0] == 10 :
    square_1_button.config(image=T10S)
if board[0] == 11 :
    square_1_button.config(image=T11S)
if board[0] == 12 :
    square_1_button.config(image=T12S)
if board[0] == 13 :
    square_1_button.config(image=T13S)
if board[0] == 14 :
    square_1_button.config(image=T14S)
if board[0] == 15 :
    square_1_button.config(image=T15S)
if board[0] == 16 :
    square_1_button.config(image=T16S)
if board[0] == 17 :
    square_1_button.config(image=T17S)
if board[0] == 18 :
    square_1_button.config(image=T18S)
if board[0] == 19 :
    square_1_button.config(image=T19S)
if board[0] == 20 :
    square_1_button.config(image=T20S)
if board[0] == 21 :
    square_1_button.config(image=T21S)
if board[0] == 22 :
    square_1_button.config(image=T22S)
if board[0] == 23 :
    square_1_button.config(image=T23S)
if board[0] >= 24 :
    square_1_button.config(image=T24S)

2 个答案:

答案 0 :(得分:1)

假设在T#S中是一个变量名,你可以这样做:

if board[0] < 24:
    square_1_button.config(image=eval("T{0}S".format(board[0])))
else:
    square_1_button.config(image=T24S)

答案 1 :(得分:0)

我建议使用一个列表:

images = [ T0S,  T1S,  T2S,  T3S,  T4S,  T5S,  T6S,  T7S,  T8S,  T9S,
           T10S, T11S, T12S, T13S, T14S, T15S, T16S, T17S, T18S, T19S,
           T20S, T21S, T22S, T23S, T24S,
]

image_index = board[0] if board[0] <= 24 else 24

square_1_button.config(image=images[image_index])

image_index = board[0] if board[0] <= 24 else 24等同于:

if board[0] <= 24:
    image_index = board[0]
else:
    image_index = 24