Kivy:在网格中分配操作/分类按钮

2024-07-21 09:11:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,分配行动的按钮,我放在一个网格在kivy。任何帮助都将不胜感激。在

我对所有的编码都是新手,但我一直在努力解决这个问题。我试着给按钮指定一个名称,但它不起作用,因为'on'u 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()

谢谢,赖安


Tags: textfromimportnonesizeitbuttonwidth
1条回答
网友
1楼 · 发布于 2024-07-21 09:11:07

所以,在第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()

App works fine

对其他具有其他功能的按钮执行相同的操作,就完成了。

相关问题 更多 >