Kivy - 动态文本标记?
我最近学习Kivy已经一个多月了,感觉很有趣,但这个问题让我很困惑。我有很多文字,需要Kivy能够高亮显示我写的词汇表中的单词,当这些单词被点击时,弹出一个窗口显示相应的定义。我有一些代码几乎可以做到这一点,但无论我点击哪个单词,弹出的窗口总是显示“crab”的定义:
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.properties import StringProperty, ListProperty, DictProperty, ObjectProperty
sentence = 'For breakfast today we will be having cheese and crab cakes and milk'
my_gloss = {'crab':'a beach-dwelling critter',
'milk':'leads to cheese when processed',
'cheese':'the processed milk of a given ungulate',
'breakfast':'the first meal of the day',
}
class GlossaryGrabber(Widget):
sentence = StringProperty(sentence)
glossary_full = DictProperty(my_gloss)
gloss_curr_key_list = ListProperty([])
new_sentence = StringProperty()
definition_popup = ObjectProperty(None)
glossary_def = StringProperty()
def highlight_terms(self):
self.gloss_curr_key_list = self.glossary_full.keys()
sent_copy = self.sentence.split(' ')
for i in self.gloss_curr_key_list:
if i in sent_copy:
sent_copy.insert(sent_copy.index(i), '[ref=][b][color=ffcc99]')
sent_copy.insert(sent_copy.index(i) + 1, '[/color][/b][/ref]')
self.glossary_def = self.glossary_full[i]
self.new_sentence = ' '.join(sent_copy)
class GlossaryApp(App):
def build(self):
g = GlossaryGrabber()
g.highlight_terms()
return g
if __name__ == '__main__':
GlossaryApp().run()
还有它对应的.kv文件:
<GlossaryGrabber>:
definition_popup: definition_popup.__self__
Label:
text: root.new_sentence
center_y: root.height/2
center_x: root.width/2
markup: True
on_ref_press: root.definition_popup.open()
Popup:
id: definition_popup
on_parent: root.remove_widget(self)
title: 'definition'
content: def_stuff
BoxLayout:
id: def_stuff
orientation: 'vertical'
Label:
text: root.glossary_def
Button:
text: 'go back'
on_release: root.definition_popup.dismiss()
显然,连接到弹出窗口内容的glossary_def字符串在每次遍历句子时都会被覆盖,但我无法传递任何形式的'ref=X',因为标签本身包含在字符串中。有没有办法给每个单词一个单独的标识符?或者有没有更好的方法来解决这个问题?我需要能够将任何字符串传递给程序作为'sentence',以及任何词汇字典。
1 个回答
2
当你点击一个引用(ref)时,kivy会告诉你是哪个引用被点击了。你需要利用这个信息来决定在弹出窗口中显示正确的文本。不过,你似乎在点击后并没有设置文本。还有一个问题是,你没有给这些引用起名字。
下面是一些修改建议,可以让它正常工作:
markup: True
on_ref_press:
root.glossary_def = root.glossary_full[args[1]]
root.definition_popup.open()
还有:
for i in self.gloss_curr_key_list:
if i in sent_copy:
sent_copy.insert(sent_copy.index(i), '[ref={}][b][color=ffcc99]'.format(i))
sent_copy.insert(sent_copy.index(i) + 1, '[/color][/b][/ref]')