Kivy-循环生成按钮的不同属性
Kivy- different attributes for for loop generated buttons
我一直在尝试根据目录中的文件数量制作多个按钮。当按下每个按钮时,它应该开始启动不同的视频文件。到目前为止,我有样本可以创建 4 个按钮,但是当我按下它时,它总是会触发最后一个按钮 on_release 功能。我试过制作一组按钮,它们会有不同的实例,但没有成功。试图获取按钮的 ID,但是当我尝试在不同的函数中返回 widget.id 时,它返回了所有 4 个按钮的 ID。
有没有明确的方法来处理这种事情。我更喜欢使用 kivy 文件,但我不知道如何在 for 循环中创建按钮。我也可以分享完整的代码和 kivy 文件,但那样会很乱。如果您需要更多信息,请告诉我。
提前致谢。
def createMultipleButton(self, dt):
root = Widget()
size_y=150;
size_x=150;
for i in range(1):
folderList = os.listdir(picture_path)
if len(folderList)==0:
time.sleep(1)
break
fileList = os.listdir(picture_path)
print fileList
for file in fileList:
x = (picture_path+"/"+file)
button = Button(id=str(file),text="" + str(file),size_hint=(None, None),height=size_y,width=size_x, pos_hint={'x': 0, 'y': 1},background_normal=x)
button.bind(on_release=lambda btn:self.VideoContainer(str(file))
print file
self.scrollview.content_layout.add_widget(button)
def VideoContainer(self,name):
mylist=name.split('.')
video = VideoPlayer(source="/home/linux/kivyFiles/kivyLogin/videoAssets/"+mylist[0]+".mp4", play=True)
video.allow_stretch=True
video.size=(500,500)
video.pos=(400,400)
self.add_widget(video)
函数体中的名称在函数执行时计算,而不是在声明时计算。 file
值是执行 lambda 函数(按下按钮)时 fileList
的最后一个元素。
你的 lambda 函数应该是:
button.bind(on_release=lambda btn, f=file: self.VideoContainer(f))
但我建议使用 functools.partial
而不是 lambda 函数来传递回调参数:
from functools import partial
button.bind(on_release=partial(self.VideoContainer, file))
def VideoContainer(self, name, btn):
#....
我一直在尝试根据目录中的文件数量制作多个按钮。当按下每个按钮时,它应该开始启动不同的视频文件。到目前为止,我有样本可以创建 4 个按钮,但是当我按下它时,它总是会触发最后一个按钮 on_release 功能。我试过制作一组按钮,它们会有不同的实例,但没有成功。试图获取按钮的 ID,但是当我尝试在不同的函数中返回 widget.id 时,它返回了所有 4 个按钮的 ID。
有没有明确的方法来处理这种事情。我更喜欢使用 kivy 文件,但我不知道如何在 for 循环中创建按钮。我也可以分享完整的代码和 kivy 文件,但那样会很乱。如果您需要更多信息,请告诉我。
提前致谢。
def createMultipleButton(self, dt):
root = Widget()
size_y=150;
size_x=150;
for i in range(1):
folderList = os.listdir(picture_path)
if len(folderList)==0:
time.sleep(1)
break
fileList = os.listdir(picture_path)
print fileList
for file in fileList:
x = (picture_path+"/"+file)
button = Button(id=str(file),text="" + str(file),size_hint=(None, None),height=size_y,width=size_x, pos_hint={'x': 0, 'y': 1},background_normal=x)
button.bind(on_release=lambda btn:self.VideoContainer(str(file))
print file
self.scrollview.content_layout.add_widget(button)
def VideoContainer(self,name):
mylist=name.split('.')
video = VideoPlayer(source="/home/linux/kivyFiles/kivyLogin/videoAssets/"+mylist[0]+".mp4", play=True)
video.allow_stretch=True
video.size=(500,500)
video.pos=(400,400)
self.add_widget(video)
函数体中的名称在函数执行时计算,而不是在声明时计算。 file
值是执行 lambda 函数(按下按钮)时 fileList
的最后一个元素。
你的 lambda 函数应该是:
button.bind(on_release=lambda btn, f=file: self.VideoContainer(f))
但我建议使用 functools.partial
而不是 lambda 函数来传递回调参数:
from functools import partial
button.bind(on_release=partial(self.VideoContainer, file))
def VideoContainer(self, name, btn):
#....