2010-01-13 72 views
0

你好我的StackOverflow的朋友。我一直在做wxPython教程和閱讀文檔,到目前爲止我喜歡它。我想先做一個簡單的應用程序。這個應用程序會做的是發送一個命令到一個微控制器打開或關閉一個繼電器。wxPython,變量沒有正確更新

我有一個全局變量去使用

(而不是在例如硬編碼COM1)的COM端口我不能讓該變量正確更新。下面是代碼:

#!/usr/bin/env python 

import wx 
from firmata import * 

# Arduino(port, baudrate=115200) 
#arduino = Arduino(comListenPort) 
#arduino.pin_mode(7, firmata.OUTPUT) 
comListenPort = 'Is not set' 
getComPort = 'Not Set' 

class ArduinoDemo(wx.Frame): 
    def __init__(self, parent, id): 
     # Main window creation 
     wx.Frame.__init__(self, parent, id, 'Demonstration of Firmata', \ 
          size = (300, 200)) 

     # Content 
     mainPanel = wx.Panel(self) 

     # Open Contact button creation 
     relayOpen = wx.Button(mainPanel, label = 'Open Contact', \ 
           pos = (25, 25), size = (120, 60)) 

     # Close Contact button creation 
     relayClosed = wx.Button(mainPanel, label = 'Close Contact', \ 
           pos = (150, 25), size = (120, 60)) 

     # Binds click event from relayOpen to openRelay 
     self.Bind(wx.EVT_BUTTON, self.closeRelay, relayClosed) 
     # Binds click event from relayClose to closeRelay 
     self.Bind(wx.EVT_BUTTON, self.openRelay, relayOpen) 

     # Get correct COM port 
     getComPort = wx.TextEntryDialog(None, 'Enter COM Port', 'COM Port', '') 
     if getComPort.ShowModal() == wx.ID_OK: 
      comListenPort = getComPort.GetValue() 
      # # Debug 
      print getComPort.GetValue() 
      print comListenPort 
      # # /Debug 


    def openRelay(self, event): 
     #arduino.digital_write(7, firmata.HIGH) 
     # # Debug 
     print comListenPort # does not print correctly 
     # # /Debug 

    def closeRelay(self, event): 
     #arduino.digital_write(7, firmata.LOW) 
     # # Debug 
     print getComPort # does not print correctly 
     # # /Debug 


if __name__ == '__main__': 
    app = wx.PySimpleApp() 
    frame = ArduinoDemo(parent = None, id = -1) 
    frame.Show() 
    app.MainLoop() 

現在我認爲有這個全局變量將最好的方式做到這一點,但我完全尋找一切建議和指針。但是,comListenPort並沒有被分配我的TextEntryDialog框的值。我知道這應該是我忽略的最愚蠢的東西。

兩個調試打印語句getComPort.GetValue()和comListenPort都打印正確的數據。當我點擊relayOpen或relayClosed按鈕時,他們會說「未設置」或「未設置」。我希望有人能拍一些感覺了我,我很傻眼了(重視啞)

再次感謝

回答

1

我覺得這裏面__init__ Python看到comListenPort作爲本地變量,而不是全球。您應該聲明它的全球使用它之前:

global comListenPort 
comListenPort = getComPort.GetValue() 

或者,你可以在值存儲爲ArduinoDemo的實例變量:

self.comListenPort = getComPort.GetValue() 
+0

謝謝,那工作。那麼在__init__或ArduinoDemo中做這件事會更好嗎? – Dan 2010-01-13 08:00:20

+0

你的意思是「全球」聲明?您應該在使用comListenPort的每個方法或函數內部使用它,以便它位於__init__中。以下是語言參考:http://docs.python.org/reference/simple_stmts.html#the-global-statement – Joril 2010-01-13 13:02:40