簡體   English   中英

此行中的 setattr() 用法

[英]setattr() usage in this line

我從某個地方得到了這段代碼,但我不明白這一行:

Dropdown.bind(on_select = lambda instance, x: setattr(mainbutton, 'text', x))

import kivy
from kivy.app import App
kivy.require("1.9.2")
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.base import runTouchApp
Dropdown = DropDown()
# creating an object out of a function
for i in range(1, 11):
    button = Button(text="Button Number " + str(i), size_hint_y=None, height=40)
    # 10 buttons with different numbers created
    button.bind(on_release=lambda button: Dropdown.select(button.text))
    # Dropdown is a function so that's why we're using Dropdown and not mainbutton that has no attribute 'select'
    # buttons bind to dropdown and if they're selected their text goes on dropdown main button
    # lambda for WHENEVER button is pressed, then when it's released something happens
    Dropdown.add_widget(button)
    # means that it is added on the layout and screen

mainbutton = Button(text="Select A Button", size_hint=(None, None), pos=(350, 300))

mainbutton.bind(on_release = Dropdown.open)
# when button is pressed and then it's released, dropdown menu opens
Dropdown.bind(on_select = lambda instance, x: setattr(mainbutton, 'text', x))
# 
runTouchApp(mainbutton)

Ok, so I don't know kivy and its not clear from the documentation that I can find, but it seems to me that kivy produces events internally and you can hook into them by binding a function of your own (a lambda in this case ) 到那個事件。

因此,當on_select事件發生時,使用兩個參數調用 function。 這些是instance, x部分。 無論調用您的 function 都提供兩個參數: instance是下拉實例, x是選擇的數據。 您的lambda然后運行表達式: setattr(mainbutton, 'text', x)我認為它與mainbutton.text = x相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM