我試圖將字符串拆分爲單詞,然後將每個單詞放在不同的標籤上。 我發現這裏是可以分割並打印出每個字碼:將字符串拆分爲不同的標籤
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()
你是什麼意思的'標籤'? – thefourtheye
如果您指的是GUI標籤,則需要指定您正在使用的GUI工具包。 – falsetru
對不起,我正在使用Kivy,忘了提。我會嘗試將每個標籤放在Scatter Widget中 –