我有这段代码,假设基于列表中的项目动态创建按钮,然后通过单击按钮将其添加到外部.txt。
我可以创建按钮,但由于某种原因,将每个按钮绑定到writeFile()函数的单个版本不起作用。我总是得到错误信息"python解决得到多个值参数'item'",这让我很困惑,因为我已经使用self作为两个函数的第一个关键字。
class MAIN(Screen):
items = ["Bike", "Car", "Boat", "Airplane"]
def __init__(self, **kw):
super().__init__(**kw)
self.list_of_btns = []
def writeFile(self, item):
with open(f"./orders/TEST", "w") as file:
file.write(f"n-{item}")
def create(self, list=items): #Creates Categorie Buttons
self.h = 1
for i in list:
self.h = self.h - 0.2
_btn = Button(text= f"{i}", size_hint=(.2,.22), pos_hint={"center_y":self.h, "center_x":.5})
add_fun = partial(self.writeFile, item=i)
_btn.bind(on_press=add_fun)
self.list_of_btns.append(_btn)
self.add_widget(_btn)
您的writeFile()
方法应该期望一个参数是被按下的Button
。尝试将该方法的签名修改为:
def writeFile(self, button, item):