我正在尝试向框布局添加一定数量的按钮,同时为它们提供以
self.pp
打开的文件行中的文本。然而我想要的是,点击任何按钮,相应的pdf文件都会通过功能opener
打开,但我后来发现,无论我按哪个按钮,打开的文件都对应于self.pp
中的最后一项,这让我认为小部件在某种程度上受到新添加的小部件的影响
这是代码
class Cours(BoxLayout):
def __init__(self,**kwargs):
self.pp=open("cours_n1.txt","r")
super().__init__(**kwargs)
self.orientation="vertical"
self.spacing = dp(5)
self.pos_hint={"top":1}
for i,line in enumerate(self.pp.readlines()):
b=Button(text=line,size_hint=(.8,None),pos_hint={"x":.1},height=(dp(40)),on_press=lambda x:self.opener(line))
self.add_widget(b)
def opener(self,line):
u = "C:\myown\computer\Assassin simulate" + line
u = u.rstrip('\n')
os.startfile(u)
在按下引用之前,不会计算 lambda 函数,因此
line
参数将始终是 line
的最后一个值。解决方法是创建一个临时参数,该参数采用 line
的当前值并在 lambda 中使用该值。像这样:
b=按钮(text=line,size_hint=(.8,None),pos_hint={"x":.1},height=(dp(40)),on_press=lambda x, ln=line:self.opener (ln))