2011-06-07 21 views
0

我正在使用o.o.p並嘗試使用pickle來加載保存在.txt文件中的行列表。我可以用醃菜保存數據,但我不確定爲什麼在初始化它後看不到'畫家'。爲什麼鹹菜在加載時看不到班上的「畫家」?

class LoadButton(MTButton): 
    def __init__(self, **kwargs): 
     super(LoadButton, self).__init__(**kwargs) 
     self.buttonLoad = kwargs.get('painter') 
    def on_release(self, touch): 
     if touch.device != 'wm_pen': 
      newLoad = self.buttonLoad 
      loadFile = open('savefiles/savetest.txt', 'rb') 
      newpainter = painter 
      scatter.remove_widget(painter) # if removed error: EOF, no data read 
      # error: local var 'painter' referenced before assignment 
      oldlines = pickle.load(loadFile) 
      painter = newpainter 
      scatter.add_widget(painter) 
      pprint.pprint(oldlines) 
      loadFile.close() 
      return True 

任何幫助都會很棒。謝謝。

+2

似乎這個誤差無關與鹹菜,不同之處在於它的原因和使用泡菜的發生在同一段代碼。 – delnan 2011-06-07 17:00:39

回答

1

這是因爲painter = newpainter創建局部變量painter,即使在調用全局painter後的部分。
做這樣的事情:

painter_ = newpainter 
scatter.add_widget(painter_) 

編輯:但是你爲什麼不使用只painter

 scatter.remove_widget(painter) 
     oldlines = pickle.load(loadFile) 
     scatter.add_widget(painter) 

編輯2: 實施例:

>>> bar = 'Bar' 
>>> def foo(): 
...  bar # This is the local bar. It has not been assigned a value yet. 
...  bar = 'Local Bar' # Here I assign a value to the bar. 
... 
>>> foo() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in foo 
UnboundLocalError: local variable 'bar' referenced before assignment 
>>> 
+0

謝謝painter_ = newpainter確實有所幫助。它取消了線條並在命令行中打印了線條,但實際上並沒有在原始全局類的「畫家」畫面上顯示線條,因此您可以再次看到圖像。不知道爲什麼。 – Joe 2011-06-08 15:57:37

+0

@Joe看到我的第一個編輯。它工作嗎? – 2011-06-08 16:43:09

相關問題