問題描述
我是 Kivy 的新手,我有一個演示我的問題的小演示片段:
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()
所以當你運行代碼時會有兩個按鈕:
So When you run the code there will be two buttons:
- 首先遍歷所有小部件并打印它們的名稱(按預期工作 - 為每個小部件返回名稱"),
- 第二個按鈕也可以遍歷所有小部件,但不是名稱而是打印它們的 id(這不起作用 - 每個 id 都返回 None).
我的問題是:
- id"不是和name"一樣的屬性嗎?
- 如何從 python 端訪問每個小部件的 id?
額外問題:
- 我可以通過它的 id 全局"訪問一個小部件(假設所有 id 都是唯一的)嗎?全局"是指例如從MyBox:"小部件訪問(在上面的代碼中)id,而不引用父子,而只是通過 id(或者可能是每個小部件唯一的任何其他屬性).我正在考慮為所有小部件創建一個字典 { id : widget object } 以便于訪問,除非有另一種我不知道的方式?強調一下 - 我試圖避免通過子父方式引用(當您以后想要更改小部件樹時,這會很混亂)并且我想用 .kv 語言生成小部件.那么最好的方法是什么?
所以這是我能想到的通過唯一全局"ID 引用小部件的最簡單方法.
So here's the easiest way I could think of to reference widgets by unique "global" id.
首先我創建了一個類,它將被我的 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
因此,只有當它具有 gid - 一個小部件類變量 - 并且它是唯一的時,才會注冊小部件.這樣我就可以在這個字典中只存儲重要的小部件.此外,從 .kv 和 python 端都可以輕松訪問它.
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.
現在我創建 gid 變量并將它們注冊到 .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)
實際上困擾我的是,我在這個全局"字典中使用 'on_pos' 事件注冊了我的小部件......我真的不喜歡,但我找不到任何可靠的方法來調用寄存器小部件初始化后的方法(on_pos 在 init 階段之后立即調用,當小部件被定位時,以后很少,所以......根據我對 kivy api 的了解,似乎是最不麻煩的方式,訂單小部件被初始化使用 .kv 語言等;所以如果有更好的方法,我會非常感謝任何指針).
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).
無論如何,通過這種方式,我可以輕松地從 .kv 將任何事件綁定到任何類中的任何方法
Anyhow, this way I can easy bind any event to any method in any class right from the .kv
要記住的一件事是 gid(全局 id)需要在全球范圍內唯一,但我發現沒有比在本地保持 id 唯一更令人不安的了(這對我來說可能同樣或什至更令人困惑).正如我所說 - 我想以不同的方式注冊小部件,但我找不到任何其他可靠的方法來做到這一點(而且我不認為 Clock 對于這些事情是可靠的).
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).
推薦答案
其實沒有.您的小部件中的 name
是一個變量,而 id
只是一個小部件引用,weakref
根據文檔.也許 python 文檔 會幫助您了解它的工作原理.您所做的是打印 id
,而不是小部件內的變量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 中解釋說,在 kv
之后解析后,將 id 收集到 ObservableDict 中.id 的工作方式類似于 python dict 鍵 id:Widget
,但只有通過字典 (ids
) 訪問.我認為 kv
解析器只是將所有 id 放入 dict 并且僅適用于它創建的 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'
即使它寫成字符串,也沒有任何變化.所以我希望解析器的行為是這樣的:抓取 id:
之后的任何整個單詞,變成一個字符串,附加到 ids
字典 <id_string>:Widget_weakref
,忘記你的 .kv
中的 id
,或者如果它再次與 .kv
一起工作,則忽略它.因此,當直接調用 id 時(不是像字典一樣的 d[key]),它的行為就像一個空/None
變量.我希望我是對的.
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.
回答第二個和第三個:
To answer the second and the third one:
如果您的意思是通過 MyBox
中的 id
直接訪問小部件,例如 SimpleLayout
,那么可以.
If you mean accessing widget by id
in MyBox
directly for example SimpleLayout
, then yes.
python 類:
self.ids.simple_layout
kv MyBox 規則:
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 全局變量那樣通過 id 訪問所有小部件,這是不可能的.您需要先訪問類/小部件,然后再訪問它的 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
這篇關于Kivy:獲取小部件 ID 并通過唯一屬性訪問小部件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!