0
我在过去的一个月左右一直在学习基维;有一个爆炸,但这个让我非常难过。我有很多文本,我需要Kivy来突出显示已写入词汇表中存在的单词,并且单击这些单词时,用适当的定义打开一个弹出窗口。我有一些代码,做差不多了这一点,但无论我点击哪个字,我只得到一个弹出与定义“螃蟹”:Kivy - 动态文字标记?
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'类型的字符串。有没有办法给每个单词一个单独的标识符?或者有更好的方法去解决这个问题吗?我需要能够通过程序任何字符串的'句子',和任何术语词典。
您的解决方案精美的工作!我发现我试图引用在on_ref_press事件之外选择的文本,因此处理所有内容都更有意义。谢谢! – jacob