Python行太长了,我怎样才能让它更具可读性?

时间:2011-04-29 20:18:06

标签: python button tkinter readability

for pic,fn,xoff in [(self.PNew,self.New,0),(self.POpen,self.Open,0),(self.PSave,self.Save,0),(self.POrigin,self.SetOrigin,20),(self.PFiducial,self.SetFiducial,0),(self.PLine,self.AddLine,20),(self.PPoint,self.AddPoint,0),(self.PMove,self.AddMove,0),(self.PCircle,self.AddCircle,0),(self.PCall,self.AddCall,0)]: Button(ButtonRow,image=pic,command=fn).pack(side=LEFT,padx=(xoff,0))

2 个答案:

答案 0 :(得分:15)

items = [
    (self.PNew, self.New, 0),
    (self.POpen, self.Open, 0),
    (self.PSave, self.Save, 0),
    (self.POrigin, self.SetOrigin, 20),
    (self.PFiducial, self.SetFiducial, 0),
    (self.PLine, self.AddLine, 20),
    (self.PPoint, self.AddPoint, 0),
    (self.PMove, self.AddMove, 0),
    (self.PCircle, self.AddCircle, 0),
    (self.PCall, self.AddCall, 0)
]
for pic, fn, xoff in items: 
    Button(ButtonRow, image=pic, command=fn).pack(side=LEFT, padx=(xoff, 0))

答案 1 :(得分:3)

你可以把它变成一个函数......

def add_button(pic, fn, xoff=0):
    Button(ButtonRow, image=pic, command=fn).pack(side=LEFT, padx=(xoff, 0))

add_button(self.PNew, self.New)
add_button(self.POpen, self.Open)
add_button(self.PSave, self.Save)
add_button(self.POrigin, self.SetOrigin, 20)
add_button(self.PFiducial, self.SetFiducial)
add_button(self.PLine, self.AddLine, 20)
add_button(self.PPoint, self.AddPoint)
add_button(self.PMove, self.AddMove)
add_button(self.PCircle, self.AddCircle)
add_button(self.PCall, self.AddCall)