2017-03-16 72 views
0

簡單的問題:按鈕返回ID,當點擊我有Kivy的Python

當我點擊我的Kivy/Python應用程序的按鈕,我想訪問該按鈕的ID。

# Kivy code 

Button: 
    id: position_1 
    on_press: app.access_button_id() 

我有各種嘗試和錯誤的嘗試,但我無法弄清楚。該按鈕嵌套如下(爲一個更大的應用程序的一部分),如果這是我的問題的一個因素:

FloatLayout: 
    AnchorLayout: 
     ScreenManager: 
      Screen: 
       BoxLayout: 
        FloatLayout: 
         Button: 
          id: position_1 
          on_press: app.access_button_id() 

這裏是我的Python代碼,返回所有的ID的。這是親如我有:

# Python code 

def access_button_id(name): 
    print(self.root.ids) 

我有問題是,我甚至不知道什麼應該在文檔中尋找,因爲我不完全理解的術語呢,所以我找不到要學習的正確信息。

編輯:

(名稱)傳遞給函數的是一些其他的功能,都沒有涉及這個問題。

回答

1

你已經知道了id - 你自己設置它。這些大多用作代碼中的硬編碼值:

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


Builder.load_string(''' 
<MyWidget>: 
    Button: 
     id: id_value_1 
     text: 'Print my id' 
     on_press: print({'id_value_1': self.proxy_ref}) 
    Button: 
     id: id_value_2 
     text: 'Print all ids' 
     on_press: print(root.ids) 
''') 


class MyWidget(BoxLayout): 
    pass 


class MyApp(App): 
    def build(self): 
     widget = MyWidget() 
     print({'id_value_1': widget.ids['id_value_1']}) 
     return widget 


if __name__ == '__main__': 
    MyApp().run() 

爲什麼你需要一個按鈕的ID,如果你已經有了它的訪問?你想達到什麼目的?


編輯

一個例子解決在註釋中提到的問題:

import random 
import functools 

from kivy.app import App 
from kivy.uix.boxlayout import BoxLayout 
from kivy.uix.popup import Popup 
from kivy.uix.button import Button 
from kivy.lang import Builder 


Builder.load_string(''' 
<MyWidget>: 
    Button: 
     text: 'B1' 
     on_press: root.open_popup(self) 
    Button: 
     text: 'B2' 
     on_press: root.open_popup(self) 
''') 

class MyWidget(BoxLayout): 
    def open_popup(self, caller): 
     fun = functools.partial(self.rename, caller) 
     popup = Popup(
      title='Test popup', 
      content=Button(
       text='rename', 
       on_press=fun 
      ), 
      size_hint=(None, None), size=(400, 400) 
     ) 
     popup.open() 

    def rename(self, caller, *args): 
     caller.text = ''.join(chr(random.randint(48, 90)) for i in range(5)) 


class MyApp(App): 
    def build(self): 
     return MyWidget() 


if __name__ == '__main__': 
    MyApp().run() 
+0

我明白了。我有大量的這些按鈕 - 在按下時他們調用一個彈出窗口,其中有一個選項列表,選擇一個選項將替換按鈕文本。每個按鈕的選項都是相同的,所以我只想編寫一個函數,將新文本應用於單擊的按鈕。目前我對每個按鈕都有一個獨特的功能,因爲我使用硬編碼的ID。 –

+0

您可以將對小部件的引用傳遞給您的彈出窗口。我添加了一個示例實現。 – Nykakin

+0

我已經得到了這個,使彈出窗口包含我的選項列表,然後單擊任意一個將隨機字符串分配給最初點擊的按鈕,所以謝謝你讓我更近了一步。現在我只需要解決如何用選擇的選項中的文本替換該隨機字符串。 –