問(wèn)題描述
我是 Kivy 的新手,我有一個(gè)演示我的問(wèn)題的小演示片段:
I'm new to Kivy and I have this little demo snippet that demonstrates my problem:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
class KivyGuiApp(App):
def build(self):
return root_widget
class MyBox(BoxLayout):
def print_ids(self, *args):
print("
ids:")
for widget in self.walk():
print("{} -> {}".format(widget, widget.id))
def print_names(self, *args):
print("
names:")
for widget in self.walk():
print("{} -> {}".format(widget, widget.name))
root_widget = Builder.load_string("""
MyBox:
id: screen_manager
name: 'screen_manager'
SimpleLayout:
id: simple_layout
name: 'simple_layout'
<SimpleLayout@BoxLayout>:
id: simple_layout_rule
name: 'simple_layout_rule'
Button:
id: button_ids
name: 'button_ids'
text: 'print ids to console'
on_release: app.root.print_ids()
Button:
id: button_names
name: 'button_names'
text: 'print names to console'
on_release: app.root.print_names()
""")
if __name__ == '__main__':
KivyGuiApp().run()
所以當(dāng)你運(yùn)行代碼時(shí)會(huì)有兩個(gè)按鈕:
So When you run the code there will be two buttons:
- 首先遍歷所有小部件并打印它們的名稱(按預(yù)期工作 - 為每個(gè)小部件返回名稱"),
- 第二個(gè)按鈕也可以遍歷所有小部件,但不是名稱而是打印它們的 id(這不起作用 - 每個(gè) id 都返回 None).
我的問(wèn)題是:
- id"不是和name"一樣的屬性嗎?
- 如何從 python 端訪問(wèn)每個(gè)小部件的 id?
額外問(wèn)題:
- 我可以通過(guò)它的 id 全局"訪問(wèn)一個(gè)小部件(假設(shè)所有 id 都是唯一的)嗎?全局"是指例如從MyBox:"小部件訪問(wèn)(在上面的代碼中)id,而不引用父子,而只是通過(guò) id(或者可能是每個(gè)小部件唯一的任何其他屬性).我正在考慮為所有小部件創(chuàng)建一個(gè)字典 { id : widget object } 以便于訪問(wèn),除非有另一種我不知道的方式?強(qiáng)調(diào)一下 - 我試圖避免通過(guò)子父方式引用(當(dāng)您以后想要更改小部件樹(shù)時(shí),這會(huì)很混亂)并且我想用 .kv 語(yǔ)言生成小部件.那么最好的方法是什么?
所以這是我能想到的通過(guò)唯一全局"ID 引用小部件的最簡(jiǎn)單方法.
So here's the easiest way I could think of to reference widgets by unique "global" id.
首先我創(chuàng)建了一個(gè)類,它將被我的 App 類繼承:
First I created a class which will be inherited by my App class:
class KivyWidgetInterface():
''' interface for global widget access '''
global_widgets = {}
def register_widget(self, widget_object):
''' registers widget only if it has unique gid '''
if widget_object.gid not in self.global_widgets:
self.global_widgets[widget_object.gid] = widget_object
def get_widget(self, widget_gid):
''' returns widget if it is registered '''
if widget_gid in self.global_widgets:
return self.global_widgets[widget_gid]
else:
return None
因此,只有當(dāng)它具有 gid - 一個(gè)小部件類變量 - 并且它是唯一的時(shí),才會(huì)注冊(cè)小部件.這樣我就可以在這個(gè)字典中只存儲(chǔ)重要的小部件.此外,從 .kv 和 python 端都可以輕松訪問(wèn)它.
So the widget will be registered only if it has gid - a widget class variable - and it is unique. This way I can store only vital widgets in this dict. Also, it is easily accessible from both .kv and python side.
現(xiàn)在我創(chuàng)建 gid 變量并將它們注冊(cè)到 .kv 中的字典:
Now i create the gid variables and register them to the dict in .kv:
<PickDirectory>:
gid: 'pick_directory'
on_pos: app.register_widget(self)
on_selection: app.get_widget('filelist').some_func()
<FileListView>:
gid: 'filelist'
on_pos: app.register_widget(self)
Button:
name: 'not important'
Button:
gid: 'tab_browse_button1'
on_pos: app.register_widget(self)
實(shí)際上困擾我的是,我在這個(gè)全局"字典中使用 'on_pos' 事件注冊(cè)了我的小部件......我真的不喜歡,但我找不到任何可靠的方法來(lái)調(diào)用寄存器小部件初始化后的方法(on_pos 在 init 階段之后立即調(diào)用,當(dāng)小部件被定位時(shí),以后很少,所以......根據(jù)我對(duì) kivy api 的了解,似乎是最不麻煩的方式,訂單小部件被初始化使用 .kv 語(yǔ)言等;所以如果有更好的方法,我會(huì)非常感謝任何指針).
Thing that bothers me actually is that I register my widgets in this "global" dictionary with the 'on_pos' event... which I really don't like, but I was unable to find any reliable way of calling a register method after the widget was initialized (on_pos is called right after the init phase, when widget is positioned and later very rarely, so... seemed like the least bothering way of doing that with my knowledge of kivy api, the order widgets are initialized with .kv language etc; so if there is a better way I'd be very grafeul for any pointers).
無(wú)論如何,通過(guò)這種方式,我可以輕松地從 .kv 將任何事件綁定到任何類中的任何方法
Anyhow, this way I can easy bind any event to any method in any class right from the .kv
要記住的一件事是 gid(全局 id)需要在全球范圍內(nèi)唯一,但我發(fā)現(xiàn)沒(méi)有比在本地保持 id 唯一更令人不安的了(這對(duì)我來(lái)說(shuō)可能同樣或什至更令人困惑).正如我所說(shuō) - 我想以不同的方式注冊(cè)小部件,但我找不到任何其他可靠的方法來(lái)做到這一點(diǎn)(而且我不認(rèn)為 Clock 對(duì)于這些事情是可靠的).
One thing to remember is that the gid (global id's) need to be unique globally, but I don't find that any more disturbing than keeping ids unique locally(which could be equally or even more confusing for me). And as I said - I'd like to register the widgets differently, but I couldn't find any other reliable way of doing this (and I don't find Clock to be reliable for such things).
推薦答案
其實(shí)沒(méi)有.您的小部件中的 name
是一個(gè)變量,而 id
只是一個(gè)小部件引用,weakref
根據(jù)文檔.也許 python 文檔 會(huì)幫助您了解它的工作原理.您所做的是打印 id
,而不是小部件內(nèi)的變量id".
Actually, no. name
in your widgets is a variable and id
is just a widget reference, weakref
according to the docs. Maybe python docs will help you understand how it works. What you did was printing id
, not a variable "id" inside a widget.
在 kivy docs 中解釋說(shuō),在 kv
之后解析后,將 id 收集到 ObservableDict 中.id 的工作方式類似于 python dict 鍵 id:Widget
,但只有通過(guò)字典 (ids
) 訪問(wèn).我認(rèn)為 kv
解析器只是將所有 id 放入 dict 并且僅適用于它創(chuàng)建的 dict.
In the kivy docs it's explained that after kv
is parsed, ids are collected into a ObservableDict. The id works like a python dict key id:Widget
but only if accessed through the dictionary(ids
). I think kv
parser just takes all ids into dict and works only with the dict it creates.
Button:
id: test
text: 'self.id'
#or
Button:
id: 'test'
text: 'self.id'
即使它寫(xiě)成字符串,也沒(méi)有任何變化.所以我希望解析器的行為是這樣的:抓取 id:
之后的任何整個(gè)單詞,變成一個(gè)字符串,附加到 ids
字典 <id_string>:Widget_weakref
,忘記你的 .kv
中的 id
,或者如果它再次與 .kv
一起工作,則忽略它.因此,當(dāng)直接調(diào)用 id 時(shí)(不是像字典一樣的 d[key]),它的行為就像一個(gè)空/None
變量.我希望我是對(duì)的.
Even if it's written like a string, nothing changes. So I expect parser to behave like this: grabs whatever whole word is after id:
, turns to a string, appends to a ids
dictionary <id_string>:Widget_weakref
, forgets about id
in your .kv
or just ignores it if it works with .kv
again. Therefore, when id is called directly(not dictionary-like d[key]), it behaves like an empty/None
variable. I hope I'm right.
回答第二個(gè)和第三個(gè):
To answer the second and the third one:
如果您的意思是通過(guò) MyBox
中的 id
直接訪問(wèn)小部件,例如 SimpleLayout
,那么可以.
If you mean accessing widget by id
in MyBox
directly for example SimpleLayout
, then yes.
python 類:
self.ids.simple_layout
kv MyBox 規(guī)則:
kv MyBox rule:
MyBox:
id: screen_manager
name: 'screen_manager'
BoxLayout:
Label:
id: my_label
text: 'test'
Button:
text: 'button'
on_release: self.text = root.ids.my_label.text
但是,要像 python 全局變量那樣通過(guò) id 訪問(wèn)所有小部件,這是不可能的.您需要先訪問(wèn)類/小部件,然后再訪問(wèn)它的 ids
字典
However, to access all widgets by their ids in way like python globals work, it's not possible. You'd need to access class/widget first and then its ids
dictionary
這篇關(guān)于Kivy:獲取小部件 ID 并通過(guò)唯一屬性訪問(wèn)小部件的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!