Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何获取kivy按钮的Id和文本值作为字符串?_Python_Kivy - Fatal编程技术网

Python 如何获取kivy按钮的Id和文本值作为字符串?

Python 如何获取kivy按钮的Id和文本值作为字符串?,python,kivy,Python,Kivy,我有一个有多个按钮的应用程序,我需要在按下按钮时以字符串的形式获取按钮的id和文本值。抓取的按钮ID和文本值将传递给另一个函数进行进一步处理。为了简单起见,我编写了这个示例程序 # main.py from kivy.app import App from kivy.uix.boxlayout import BoxLayout ######################################################################## class KVMy

我有一个有多个按钮的应用程序,我需要在按下按钮时以字符串的形式获取按钮的id和文本值。抓取的按钮ID和文本值将传递给另一个函数进行进一步处理。为了简单起见,我编写了这个示例程序

# main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

########################################################################
class KVMyHBoxLayout(BoxLayout):
    pass


########################################################################
class ExampleApp(App):
    def Pressbtn(self, *args):
        print'Pressed button'
    #----------------------------------------------------------------------
    def build(self):

        return KVMyHBoxLayout()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = ExampleApp()
    app.run()
kv文件

<MyButton@Button>:
    color: .8,.9,0,1
    font_size: 32

<KVMyHBoxLayout>:
    orientation: 'vertical'
    MyButton:
        id:"idBtn1"
        text: "Btn1"
        background_color: 1,0,0,1
        on_press:app.Pressbtn()
    MyButton:
        id:"idBtn2"
        text: "Btn2"
        background_color: 0,1,0,1
        on_press:app.Pressbtn()
    Label:
        text: "ID"
        background_color: 0,0,1,1
    Label:
        text: "Text"
        background_color: 1,0,1,1
:
颜色:.8,9,0,1
字体大小:32
:
方向:“垂直”
我的按钮:
id:“idBtn1”
文本:“Btn1”
背景颜色:1,0,0,1
按:app.Pressbtn()
我的按钮:
id:“idBtn2”
文本:“Btn2”
背景颜色:0,1,0,1
按:app.Pressbtn()
标签:
文本:“ID”
背景颜色:0,0,1,1
标签:
文本:“文本”
背景颜色:1,0,1,1

当按下按钮时,其对应的id和文本值将显示在id和文本标签中。当前,按下按钮时,上述代码仅打印按下的按钮。我想知道如何以pythonical方式获取button的id和文本值。

首先,当从kv调用button实例时,必须将其显式地传递给该方法:

on_press: app.Pressbtn(self)
然后,您可以使用实例引用修改按钮或查看其属性,您不需要
id
。如果要获取
id
,只能使用按钮父级的
id
字典

基于您的代码的示例:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

kv_file = '''
<MyButton@Button>:
    color: .8,.9,0,1
    font_size: 32

<KVMyHBoxLayout>:
    orientation: 'vertical'
    MyButton:
        id:"idBtn1"
        text: "Btn1"
        background_color: 1,0,0,1
        on_press:app.Pressbtn(self)
    MyButton:
        id:"idBtn2"
        text: "Btn2"
        background_color: 0,1,0,1
        on_press:app.Pressbtn(self)
    Label:
        id: lobj
        text: "Object"
        background_color: 1,0,1,1

    Label:
        id: lid
        text: "ID"
        background_color: 0,0,1,1
    Label:
        id: ltext
        text: "Text"
        background_color: 1,0,1,1
'''


class KVMyHBoxLayout(BoxLayout):
    pass

class ExampleApp(App):
    def Pressbtn(self, instance):
        instance.parent.ids.lobj.text = str(instance)
        instance.parent.ids.ltext.text = instance.text
        instance.parent.ids.lid.text= self.get_id(instance)

    def get_id(self,  instance):
        for id, widget in instance.parent.ids.items():
            if widget.__self__ == instance:
                return id

    def build(self):
        Builder.load_string(kv_file)
        return KVMyHBoxLayout()

if __name__ == "__main__":
    app = ExampleApp()
    app.run()
从kivy.app导入应用
从kivy.uix.boxlayout导入boxlayout
从kivy.lang导入生成器
kv_文件=“”
:
颜色:.8,9,0,1
字体大小:32
:
方向:“垂直”
我的按钮:
id:“idBtn1”
文本:“Btn1”
背景颜色:1,0,0,1
按:应用程序按BTN(自身)
我的按钮:
id:“idBtn2”
文本:“Btn2”
背景颜色:0,1,0,1
按:应用程序按BTN(自身)
标签:
id:lobj
文本:“对象”
背景颜色:1,0,1,1
标签:
id:盖子
文本:“ID”
背景颜色:0,0,1,1
标签:
id:ltext
文本:“文本”
背景颜色:1,0,1,1
'''
KVMyHBoxLayout类(BoxLayout):
通过
类示例示例应用程序(应用程序):
def Pressbtn(自身,实例):
instance.parent.ids.lobj.text=str(实例)
instance.parent.ids.ltext.text=instance.text
instance.parent.ids.lid.text=self.get\u id(实例)
def get_id(自身,实例):
对于id,instance.parent.ids.items()中的小部件:
如果widget.\uuuu self\uuuu==实例:
返回id
def生成(自):
Builder.load\u字符串(kv\u文件)
返回KVMyHBoxLayout()
如果名称=“\uuuuu main\uuuuuuuu”:
app=示例app()
app.run()
输出:

编辑:

如果在.py文件中定义小部件(按钮),则不需要将实例传递给函数,它将自动作为参数传递:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView


class FirstScreen(Screen):
    def __init__(self,**kwargs):
        super(FirstScreen, self).__init__(**kwargs)    
        layout=BoxLayout(orientation="vertical",size_hint_y= None)
        layout.bind(minimum_height=layout.setter('height'))                
        for i in range(50):
                btn = Button(text="Button"+str(i),
                             id=str(i),
                             size_hint=(None, None),
                             on_press=self.Press_auth)               #<<<<<<<<<<<<<<<<           
                layout.add_widget(btn)
        root = ScrollView()
        root.add_widget(layout)
        self.add_widget(root)

    def Press_auth(self,instance):     
        print(str(instance))

class TestScreenManager(ScreenManager):
    def __init__(self,  **kwargs):
        super(TestScreenManager,  self).__init__(**kwargs)
        self.add_widget(FirstScreen())

class ExampleApp(App):
    def build(self):           
        return TestScreenManager()

def main():
    app = ExampleApp()
    app.run()

if __name__ == '__main__':
    main()
从kivy.app导入应用
从kivy.uix.boxlayout导入boxlayout
从kivy.uix.screenmanager导入screenmanager,屏幕
从kivy.uix.button导入按钮
从kivy.uix.scrollview导入scrollview
类第一屏幕(屏幕):
定义初始(自我,**kwargs):
超级(第一屏,自我)。\uuuuuuuuuuuuuuuuu初始(**kwargs)
布局=框布局(方向=“垂直”,大小\u提示\u y=无)
layout.bind(最小高度=layout.setter('height'))
对于范围(50)内的i:
btn=按钮(text=“Button”+str(i),
id=str(i),
大小提示=(无,无),

在_press=self.press_auth)#上,您可以使用回调函数来执行以下操作。在您的KV文件中:

 ToggleButton:
     text: 'Label'
     id: halftimebutton
     on_state: root.callback(self)
然后在.py文件中可以执行以下操作:

def callback_halftime_state(self, instance):
    if instance.state == 'down':
        self.halftime == True
    else:
        self.halftime == False

这当然是显示instance.state-但它可以是Kivy公开的按钮的任何属性实例.text实例.id等。

示例要在按钮单击时获取按钮文本:

class MainApp(MDApp):
def build(self):

    VB = BoxLayout(orientation='vertical', padding=50,spacing="10")

    Atbtn = Button(text="AT (Automata Theory)", font_size="25sp")
    Atbtn.bind(on_press=self.callback)

    Pybtn = Button(text="Python", font_size="25sp")
    Pybtn.bind(on_press=self.callback)


    VB.add_widget(Atbtn)
    VB.add_widget(Pybtn)

    return VB

def callback(self, instance):
    print(instance.text)

感谢它的工作原理我正在屏幕内使用按钮当我按下按钮时,它返回屏幕的对象
@Eka此代码工作,即使按钮位于
屏幕内的布局中(除了获取
id
)。如果您无法使其正常工作,请通过添加代码来编辑问题,看看我是否可以帮助您。这是我的代码,我正在screen类中创建一个带有按钮的Scrollview boxlayout。这个
on\u press=lambda:self.press\u auth(self)
我从一些示例代码中获取它,它检测到press事件,但它传递的对象是
@Eka您只需要将
on\u press=lambda替换为:self.press\u auth(self)
on\u press=self.press\u auth
。我编辑了答案。致以最良好的问候。谢谢。它解决了我的问题。最初我在self.press\u auth()上尝试了这个
。这使我犯了一个错误。再次感谢你