2016-03-10 77 views
1

我想基於外部文件爲Python和Kivy動態創建一些按鈕。在Python中循環內動態創建變量

到目前爲止,我設法網絡抓取文件,讀取它並創建小部件。問題是我需要這些小部件有一個唯一的var名稱,我看不到一種方法來實現這一點。

def build(self): 
    #main layout 
    menu_box = BoxLayout(orientation="horizontal") 
    #web scraping 
    try: 
     WebLeida = request.urlopen("http://coznothingisforever.webs.com/Yoloplanner/Yoloplanner.txt").read().decode('utf8') 
     WebParsed = ast.literal_eval(WebLeida) 
     #for each item 
     for i in WebParsed: 
      #create a button 
      boton = Button(font_size=16, 
          size_hint_y=None, 
          height=100, 
          text=i["dia"] + " - " + i["hora"]) 
      #bind the events 
      boton.bind(print("testing")) 
      #add the new created button to the layout 
      menu_box.add_widget(boton) 
    except: 
     print("Something went wrong") 
    #run the main layout 
    return menu_box 

這樣做的問題是,所有的按鈕將被命名爲「BOTON」,所以,當我需要使用特定的功能,如boton.bind程序將不知道該使用哪一個。

這是希望的前哨,但具有獨特的變種名稱: enter image description here

有什麼建議?
另外,Web抓取是實現這一目標的最佳方式嗎?

+0

[This](http://stackoverflow.com/questions/35856891/how-can-i-make-a-lot-of-buttons-at-dynamic-in-kv-language/35867156#35867156 )可能對您有所幫助。 – jligeza

+0

這是有點粗暴,但你有嘗試的內部:'exec(「self.boton」+ str(i))= ...' ? – Mixone

回答

1

什麼,我不知道爲什麼沒有人張貼了這個作爲一個答案,即使它是在python標籤。 kivy中的每個小部件都是一個對象,因此它在創建時就在那裏,而且您不必直接使用變量,例如只在一行中使用Button(...)。因此它在kv文件,這樣容易設計你的應用程序中是這樣的:

<Root_widget>: 
    SomeWidget: 
     Button_1: 
     ... 
     Button_N: 

沒有變,但是如果你願意,你可以通過id你的小部件,然後將其收集到ids字典。還有一些與ID相似的東西。可以自由創建自己的字典,並添加每一個你喜歡按鈕就可以在這樣的方法:

my_buttons['new_button'] = Button(font_size=16, size_hint_y=None, height=100, 
            text=i["dia"] + " - " + i["hora"]) 

如果綁定,它就會像<xyz object at somewhere>.bind()並在例如,它會是這樣的:

from kivy.app import App 
from kivy.uix.button import Button 
from kivy.uix.boxlayout import BoxLayout 
from functools import partial 

class Box(BoxLayout): 
    buttons={} 
    def __init__(self, **kw): 
     super(Box, self).__init__(**kw) 
     for i in range(10): 
      self.buttons[str(i)]=Button(text=str(i)) 
      self.add_widget(self.buttons[str(i)]) 
      self.buttons[str(i)].bind(on_release=partial(self.ping, str(i))) 
    def ping(self, *arg): 
     print 'test',str(arg) 
class My(App): 
    def build(self): 
     return Box() 
My().run() 
+0

我正在尋找這樣的東西,謝謝你:P – Saelyth

2

你關心什麼是id? 如果它只是唯一性,然後

import uuid 
id = str(uuid.uuid4()) 

如果你關心的ID是可以做

id_template = 'button_id_{0}' 
count = 1 
for i in WebParsed: 
    button_id = id_template.format(count) 
    count += 1