問題描述
假設我正在構建一個井字游戲(因為它與結構非常相似)我希望結果顯示在帶有新游戲按鈕的彈出窗口中,并且我希望此彈出窗口允許我訪問設置(使用另一個按鈕)并更改它們,始終保持在彈出窗口中,然后離開并最終關閉它并開始一個新游戲.
Let's pretend I am building a tic-tac-toe game (becouse it's pretty similar as a structure) I want the result to be shown in a popup, with a new game button, and I want this popup to let me access settings (with another button) and change them, always staying within the popup, then leave and finally close it and start a new game.
我希望我可以保持有序,因此有一個單獨的彈出窗口類,我可以在其中構建我的自定義彈出窗口.
I wish i could keep things ordered and therefore have a separate popup class where i can build my custom popup.
很明顯,我有 newgame 方法和 reset 方法作為我的游戲網格類的方法.另一方面,更改設置的方法是在自定義設置類上
I have the newgame method and reset method as method of my game-grid class, as obvious. Methods for changing settings are, on the other hand, on a custom settings class
在設計彈出類時,如何將其按鈕(例如新游戲)綁定到完全不同的類中包含的方法?我查看了一些 kv 示例,他們通常使用 root.blabla.method 來訪問位于同一棵樹的不同位置(在 .kv 文件中)的方法,但這里我試圖達到的方法超出了樹!
While designing the popup class how can I bind it's buttons (e.g new game) to methods that are contained on a completly different class? I've looked on some kv examples and they usually use root.blabla.method to acces a method that is in a different position of the same tree (in the .kv file) but here the methods I am trying to reach are out of the tree!
我會嘗試放一些示例代碼以使其更清晰
I'll try to put some example code to make it more clear
class Settings():
def changeSettings(self):
....
class GmeGrid(GridLayout):
def newGame(self):
....
def reset(self):
...
class customPopup(Popup):
pass
然后,在一個 .kv 文件上,我希望我可以將一些彈出按鈕綁定到 newGame 并更改設置方法
Then, on a .kv file I wish I could bind some popup's buttons to the newGame and change settings methods
這里的問題是我應該將 popop 類上的按鈕綁定到完全不同的類的方法上,但我不知道該怎么做(尤其是在 .kv 文件上)
The problem here is that I should bind buttons on the popop class to the mothods of completly different class and I don't know how to to that (on the .kv file especially)
推薦答案
只要widget已經完全實例化并添加到widget樹中,就可以使用self.parent
來訪問widget的父母.不過,您可能會考慮傳遞引用:
As long as the widget has been fully instantiated and added to the widget tree, you can use self.parent
to access the widget's parent. You might look into passing references instead though:
Builder.load_string('''
<CustomPopup>:
BoxLayout:
orientation: 'vertical'
# some settings stuff here
BoxLayout:
orientation: 'horizontal'
Button:
text: 'New Game'
on_press: root.do_new_game()
''')
class CustomPopup(Popup):
settings_widget = ObjectProperty()
new_game = ObjectProperty()
def do_new_game(self):
self.settings_widget.some_property = some_value
self.dismiss()
self.new_game()
p = CustomPopup(settings_widget=my_widget, new_game=mygame.newGame)
p.open()
這比假設父級具有設置更好,因為如果您更改保存設置的位置,您只需要更改一個引用.
This is better that assuming the parent has the settings, because if you change where you keep the settings, you just need to change one reference.
這篇關于Kivy:訪問不同類的方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!