问题描述
假设我正在构建一个井字游戏(因为它与结构非常相似)我希望结果显示在带有新游戏按钮的弹出窗口中,并且我希望此弹出窗口允许我访问设置(使用另一个按钮)并更改它们,始终保持在弹出窗口中,然后离开并最终关闭它并开始一个新游戏.
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:访问不同类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!