2012-03-24 29 views
0

我從來沒有在Python代碼,並試圖從Javascrpt/SVG切換。被Python中的變量作用域和流程混淆,我會理解這些基本代碼的任何修正,以便通過mousedown和mouseup事件繪製矩形。除非您沒有在代碼中指出我的錯誤,否則請不要將指示鏈接到該鏈接。wxPython基本開羅繪圖通過鼠標拖動

如果 == 「主要」: 進口WX 進口數學

class myframe(wx.Frame): 
    pt1 = 0 
    pt2 = 0 
    def __init__(self): 
     wx.Frame.__init__(self, None, -1, "test", size=(500,400)) 
     self.Bind(wx.EVT_LEFT_DOWN, self.onDown) 
     self.Bind(wx.EVT_LEFT_UP, self.onUp) 
     self.Bind(wx.EVT_PAINT, self.drawRect) 

    def onDown(self, event):   
     global pt1 
     pt1 = event.GetPosition() # firstPosition tuple 

    def onUp(self, event):   
     global pt2 
     pt2 = event.GetPosition() # secondPosition tuple 

    def drawRect(self, event): 
     dc = wx.PaintDC(self) 
     gc = wx.GraphicsContext.Create(dc) 
     nc = gc.GetNativeContext() 
     ctx = Context_FromSWIGObject(nc) 

     ctx.rectangle (pt1.x, pt1.y, pt2.x, pt2.y) # Rectangle(x0, y0, x1, y1) 
     ctx.set_source_rgba(0.7,1,1,0.5) 
     ctx.fill_preserve() 
     ctx.set_source_rgb(0.1,0.5,0) 
     ctx.stroke() 


app = wx.App() 
f = myframe() 
f.Show() 
app.MainLoop() 

回答

1

星爺,你有一個範圍問題(加 - 你的代碼無法正確顯示)。

讓我給你一個簡單的例子如何使用成員和全局的蟒蛇:

# Globals are defined globally, not in class 
glob1 = 0 

class C1: 
    # Class attribute 
    class_attrib = None # This is rarely used and tricky 

    def __init__(self): 
     # Instance attribute 
     self.pt1 = 0 # That's the standard way to define attribute 

    def other_method(self): 
     # Use of a global in function 
     global glob1 
     glob1 = 1 

     # Use of a member 
     self.pt1 = 1 

# Use of a class attribute 
C1.class_attrib = 1 

在你的代碼是混合所有類型的變量。我想你應該只是做PT1和PT2實例的屬性,讓你的代碼看起來像:

class MyFrame(wx.Frame): 
    def __init__(self): 
     wx.Frame.__init__(self, None, -1, "test", size=(500,400)) 
     self.pt1 = self.pt2 = 0 
     ... 

    def onDown(self, event):   
     self.pt1 = event.GetPosition() # firstPosition tuple 

    ... 

你可以考慮讀一些通用教程像this one,學習Python作用域是如何工作的。

+0

非常感謝。 Python與JavaScript非常不同,但我應該學習它。我現在修復了我的代碼。 – Alex 2012-03-24 17:27:16

+0

Python與其他語言有點不同。因爲這是值得去嘗試官方教程,他們不是太無聊,你會學到很多Python特定的東西。 – Tupteq 2012-03-24 17:43:51