简体   繁体   中英

wxPython basic Cairo drawing by mouse drag

I have never code in Python and trying to switch from Javascrpt/SVG. Being confused by variable scope in Python and process flow, I will appreciate any correction to those basic code to make it draw rectangle by mousedown and mouseup events. Please don't put links to instructions unless you didn't point me on errors in code.

if name ==" main ": import wx import math

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()

Yeh, you have a problem with scopes (plus - your code isn't showing properly).

Let me give you a short example how to use members and globals in 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

In your code you are mixing all types of variables. I think you should just make pt1 and pt2 instance attributes, so your code would look like:

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

    ...

You could consider reading some general tutorial like this one , to learn how Python scoping works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM