2014-03-06 24 views
0

我試圖將字符串拆分爲單詞,然後將每個單詞放在不同的標籤上。 我發現這裏是可以分割並打印出每個字碼:將字符串拆分爲不同的標籤

my_phrase="The split method returns a list of the words in the string" 
my_split_words = my_phrase.split() 
for each_word in my_split_words: 
    print each_word 

但如何讓一個循環,而不是印刷,生成標籤?

我在GUI中使用Python 2.7與Kivy。提前致謝!

很抱歉,如果我的格式是錯誤的,第一篇文章在這裏:)

編輯1:

我的代碼看起來像現在這種權利:

from kivy.app import App 

from kivy.uix.scatter import Scatter 
from kivy.uix.label import Label 
from kivy.uix.floatlayout import FloatLayout 
from kivy.uix.boxlayout import BoxLayout 

class TestApp(App): 
    def build(self): 
     b = BoxLayout(orientation='vertical') 
     f = FloatLayout() 
     s = Scatter() 
     l = [Label(text=word) for word in "The split method returns a list of the words in the string".split()] 

     f.add_widget(s) 
     s.add_widget(l) 
     b.add_widget(f) 
     return b 

if __name__ == "__main__": 
    TestApp().run() 

@Hugh博思韋爾答案後,我試圖替換舊的L標籤上的多個標籤生成的分割,但它沒有工作:T

編輯2: 現在我的代碼工作正常,謝謝大家。 它接受來自用戶的輸入,然後將字符串拆分爲分散標籤。 這是一個有點混亂,但它會做的工作!

class TestApp(App): 
    def build(self): 
     ti = TextInput(font_size=30, 
         size_hint_y=None, 
         height=50, 
         text='default') 
     b = BoxLayout(orientation='vertical') 
     f = FloatLayout() 

     def SplitIntoLabels(*args): 
      f.clear_widgets() 
      for word in new_list: 
       s = Scatter(size_hint_x=None, size_hint_y=None, do_rotation=False) 
       l = Label(text=word, font_size=50) 
       s.add_widget(l) 
       f.add_widget(s) 
       s.size=l.size 

     ti.bind(text=SplitIntoLabels) 

     b.add_widget(ti) 
     b.add_widget(f) 

     return b 

if __name__ == "__main__": 
    TestApp().run() 
+0

你是什麼意思的'標籤'? – thefourtheye

+0

如果您指的是GUI標籤,則需要指定您正在使用的GUI工具包。 – falsetru

+0

對不起,我正在使用Kivy,忘了提。我會嘗試將每個標籤放在Scatter Widget中 –

回答

2

你跑s.add_widget(l),但l不是一個小工具,它是一個列表..這顯然是行不通的。

你,而不是要像做

for widget in l: 
    s.add_widget(widget) 

此外,當你說「但它沒有工作」,它通常是有用的說如何它沒有工作,可能連同追溯。在這種情況下,您應該可能會得到一個WidgetException,其中包含有關該問題的一些文本,這可以幫助您進行調試。或者也許還有另一個錯誤,我不會錯過更多的信息。

+0

謝謝!現在它以我認識的方式工作。 但是Scatter的行爲方式與我最初的理解不同,所有標籤在相同的散點圖中重疊在一起,並且不可能分開移動它們。 我認爲我需要使循環生成一個新的分佈與一個新的標籤內'每個word.for t.split()中的單詞:f.add_widget(s)s.add_widget(Label(text = word) )'但是這樣我收到一個屬性錯誤:「NoneType」對象沒有屬性「綁定」。 如果問的不是太多,你能幫助我嗎? –

+0

我不關注你的新代碼是什麼,你可以將它添加到你的原始文章? – inclement

+0

它現在正在工作,在原帖中添加了代碼。謝謝你的幫助! –

2
from kivy.uix.label import Label 

my_phrase = "The split method returns a list of the words in the string" 

labels = [Label(text=word) for word in my_phrase.split()] 

編輯:

for lab in labels: 
    s.add_widget(lab) 

,或者更直接,

for word in my_phrase.split(): 
    s.add_widget(Label(text=word)) 
+0

我試圖用我的代碼(以愚蠢的方式)將您的想法替換爲舊標籤,當然這並不奏效。你知道我需要改變什麼嗎?感謝您的回答! –

相關問題