我遇到了将操作分配给我在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()
谢谢,Ryan
答案 0 :(得分:0)
因此,在第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()
对其他具有其他功能的按钮执行相同的操作,您就完成了。