Kivy:在网格中分配动作/分类按钮
Posted
技术标签:
【中文标题】Kivy:在网格中分配动作/分类按钮【英文标题】:Kivy: assigning actions/classifying buttons in grid 【发布时间】:2017-10-29 01:07:19 【问题描述】:我在将操作分配给我在 kivy 中的网格中放置的按钮时遇到问题。任何帮助将不胜感激。
我对所有编码都是新手,但我一直在努力解决这个问题。我试图为按钮分配一个名称,但它不起作用,因为“on_press”函数不适用于字符串,只能用于按钮。有什么方法可以将网格中的字符串分类为按钮,还是我做错了一切?我希望每个按钮都执行不同的操作,因此它们不能被归类为同一事物。
这是我的代码:
import kivy
kivy.require('1.10.0')
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.button import Button
class MyApp(App):
def build(self):
def callback(instance):
print('The button 1 is being pressed' % instance.text)
# test 1: I dont think this works because it doesn't work with the grid structure but I tried it anyways
# btn1 = Button(background_color=blue, text='a', size_hint_x=None, width=butw)
# test 2: I don't think it works because it is not classified as a button, but a string.
# btn1 = "layout.add_widget(Button(background_color=blue, text='a', size_hint_x=None, width=butw))"
btn1.bind(on_press=callback)
layout = GridLayout(cols=1, rows=28, row_force_default=True, row_default_height=buth)
layout.add_widget(Button(background_color=blue, text='a', size_hint_x=None, width=butw))
layout.add_widget(Button(background_color=blue2, text='b', size_hint_x=None, width=butw))
layout.add_widget(Button(background_color=blue, text='c', size_hint_x=None, width=butw))
# cont.
return layout
MyApp().run()
谢谢,瑞恩
【问题讨论】:
【参考方案1】:所以,在第 12 行,print('The button 1 is being pressed' % instance.text)
,您尝试格式化字符串,但您没有指定将实例文本放在何处。否则,我编辑的这段代码(请下次从示例中删除所有不需要的代码)工作正常,当按下“a”按钮时它会打印:
import kivy
kivy.require('1.10.0')
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button
class MyApp(App):
def build(self):
def callback(instance):
print('The button 1 is being pressed', instance.text)
# test 1: I dont think this works because it doesn't work with the grid structure but I tried it anyways
btn1 = Button(text='a', size_hint_x=None, width=30)
btn1.bind(on_press=callback)
layout = GridLayout(cols=1, rows=28)
layout.add_widget(btn1)
layout.add_widget(Button(text='b', size_hint_x=None, width=30))
layout.add_widget(Button(text='c', size_hint_x=None, width=30))
return layout
MyApp().run()
对具有其他功能的其他按钮执行相同操作,就完成了。
【讨论】:
以上是关于Kivy:在网格中分配动作/分类按钮的主要内容,如果未能解决你的问题,请参考以下文章