問題描述
我對(duì)面向?qū)ο缶幊痰睦斫庥悬c(diǎn)不穩(wěn)定,所以如果你有任何鏈接可以幫助解釋這些概念,我會(huì)很高興看到它們!
My understanding of Object Orientated Programming is a little shaky so if you have any links that would help explain the concepts it would be great to see them!
我已經(jīng)稍微縮短了代碼.基本原則是我有一個(gè)以主 Controller 類的實(shí)例開始的游戲.當(dāng)游戲打開時(shí),Popup 類被打開.事件發(fā)生如下:
I've shortened the code somewhat. The basic principle is that I have a game that starts with an instance of the main Controller class. When the game is opened the Popup class is opened. The events happens as follows:
- 點(diǎn)擊彈窗上的開始按鈕
- 方法 start_click() 運(yùn)行
- 調(diào)用Controller實(shí)例中的start_game()方法
- 這又將原始控制器實(shí)例中的游戲狀態(tài)更改為真"
我的問題在于第 3 步.我收到的錯(cuò)誤消息是:
My problem is with step 3. The error message I get is:
TypeError: unbound method start_game() must be called with Controller
instance as first argument (got nothing instead)
我想 StartPopUp 類中需要對(duì) Controller 類進(jìn)行一些引用.但我不太明白如何創(chuàng)建該參考?
I guess there needs to be some reference to the Controller class in the StartPopUp class. But I don't quite understand how to create that reference?
import kivy
kivy.require('1.8.0')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.clock import Clock
from kivy.properties import BooleanProperty, NumericProperty, ObjectProperty
from kivy.uix.popup import Popup
from kivy.lang import Builder
Builder.load_string('''
<StartPopUp>
size_hint: .2, .2
auto_dismiss: False
title: 'Welcome'
Button:
text: 'Play'
on_press: root.start_click()
on_press: root.dismiss()
''')
class StartPopUp(Popup):
def __init__(self, **kw):
super(StartPopUp, self).__init__(**kw)
def start_click(self):
Controller.start_game()
class Controller(Widget):
playing_label = BooleanProperty(False) #Intitial phase of game is off
def __init__(self, **kw):
super(Controller, self).__init__(**kw)
def start_popup(self, dt):
sp = StartPopUp()
sp.open()
def start_game(self):
self.playing_label = True
print self.playing_label
class MoleHuntApp(App):
def build(self):
game = Controller()
Clock.schedule_once(game.start_popup, 1)
return game
if __name__ == '__main__':
MoleHuntApp().run()
提前致謝!
推薦答案
可以這樣傳遞實(shí)例
class StartPopUp(Popup):
def __init__(self, controller, **kw):
super(StartPopUp, self).__init__(**kw)
self.controller = controller
def start_click(self):
self.controller.start_game()
在控制器中
def start_popup(self, dt):
sp = StartPopUp(self)
sp.open()
這篇關(guān)于從現(xiàn)有實(shí)例調(diào)用方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!