本文介绍了如何用kv语言制作动态的很多按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用kv语言动态制作很多按钮。但现在我不能......
我现在将在这里显示来源。
BoxLayout:
orientation:'vertical'
pos:root.pos
size:root.size
GridLayout:
行:2
间距:5
填充:5
按钮:
文本:X0
on_press:root.X 0)
按钮:
文本:X1
on_press:root.X(1)
我想像代码
BoxLayout:
orientation:'vertical'
pos:root.pos
size:root.size
GridLayout:
rows:2
间距:5
padding:5
为i
按钮:
文本:X#{i}
on_press:root.X(i)
我该怎么办?
解决方案
不可能用kv语言,除了做一些脏的黑客。
要动态创建一组按钮,请使用或将它们添加到py文件中的循环中。
示例:
从functools导入部分
类MyGrid(GridLayout):
def __init __(self,** kwargs):
super(MyGrid,self).__ init __(** kwargs)
self.add_buttons()
def add_buttons(self)
for x in xrange(5):
button = Button(
text ='X'+ str(i),
on_press = partial(self.X,number = i )
)
self.add_widget(button)
def X(self,caller,number):
print caller,number
I want to make a lot of Buttons at dynamic in kv language.But now I cannot......I will show now source under this.
BoxLayout:
orientation: 'vertical'
pos: root.pos
size: root.size
GridLayout:
rows: 2
spacing: 5
padding: 5
Button:
text: "X0"
on_press: root.X(0)
Button:
text: "X1"
on_press: root.X(1)
I want to make like under code
BoxLayout:
orientation: 'vertical'
pos: root.pos
size: root.size
GridLayout:
rows: 2
spacing:5
padding:5
for i
Button:
text: "X#{i}"
on_press: root.X(i)
How can I do?
解决方案
Such loops aren't possible in kv language, other than doing some dirty hacks.
To create a set of buttons dynamically, either use ListView or add them in a loop inside a py file.
Example:
from functools import partial
class MyGrid(GridLayout):
def __init__(self, **kwargs):
super(MyGrid, self).__init__(**kwargs)
self.add_buttons()
def add_buttons(self):
for i in xrange(5):
button = Button(
text='X' + str(i),
on_press=partial(self.X, number=i)
)
self.add_widget(button)
def X(self, caller, number):
print caller, number
这篇关于如何用kv语言制作动态的很多按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!