我正在尝试将字符串拆分为单词,然后将每个单词放在不同的标签上。 我在这里找到了一个可以分割和打印每个单词的代码:
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
但是如何制作循环而不是打印,生成标签?
我正在使用Python 2.7和Kivy一起使用GUI。提前谢谢!
对不起,如果我的格式错误,请先在此处发帖:)
修改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 Bothwell回答之后我试图替换分裂时生成的多个标签的旧L标签,但它不起作用:T
EDIT2: 现在我的代码工作正常,谢谢大家。 它接受来自用户的输入,然后将字符串拆分为分散标签。 它有点乱,但它会起作用!
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 :(得分: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))
答案 1 :(得分:2)
您运行s.add_widget(l)
,但l
不是小部件,它是一个列表......所以这显然不起作用。
你想要做类似
的事情for widget in l:
s.add_widget(widget)
此外,当你说'但它不起作用'时,通常会说 它不起作用,可能还有追溯。在这种情况下,你应该得到一个WidgetException
,包括一些关于问题的文本,这应该可以帮助你调试它。或者也许还有另一个错误,我不会错过更多信息。