通过鼠标拖动wxPython基本开罗绘图

时间:2012-03-24 09:56:42

标签: python drawing wxpython cairo

我从未在Python中编写代码并尝试从Javascrpt / SVG切换。由于Python和流程中的变量范围混淆,我将欣赏对这些基本代码的任何更正,以使其通过mousedown和mouseup事件绘制矩形。除非您没有指出代码中的错误,否则请不要将链接放到指令中。

如果名称 ==“主要”:     导入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 个答案:

答案 0 :(得分:1)

是的,你有范围问题(加上 - 你的代码没有正确显示)。

让我举一个简短的例子,说明如何在python中使用成员和全局变量:

# 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范围的工作原理。

相关问题