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