使用鼠标位置在wxPython中绘制一条线

时间:2018-01-23 22:38:02

标签: python wxpython

我试图在wxPython中制作程序,这会在我点击窗口的位置绘制一条线,但它不起作用,我实际上不知道为什么。我怎么写这个,它会起作用?

import wx
global coord
coord = (30, 30)
class MyFrame(wx.Frame):
    """create a color frame, inherits from wx.Frame"""
global coord
def __init__(self, parent):
    # -1 is the default ID
    wx.Frame.__init__(self, parent, -1, "Click for mouse position", size=(400,300),
                     style=wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE)
    self.SetBackgroundColour('Goldenrod')
    self.SetCursor(wx.StockCursor(wx.CURSOR_PENCIL))

    # hook some mouse events
    self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
    self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
    self.Bind(wx.EVT_PAINT, self.OnPaint)


def OnLeftDown(self, event):
    global coord
    """left mouse button is pressed"""
    pt = event.GetPosition()  # position tuple
    print pt
    coord = pt
    self.SetTitle('LeftMouse = ' + str(pt))

def OnRightDown(self, event):
    global coord
    """right mouse button is pressed"""
    pt = event.GetPosition()
    coord = pt
    print pt

    self.SetTitle('RightMouse = ' + str(pt))


def OnPaint(self, event):
    global coord
    dc = wx.PaintDC(self)
    dc.Clear()
    dc.SetPen(wx.Pen(wx.BLACK, 4))
    dc.DrawLine(0, 0, int(str(coord[0])), int(str(coord[1])))

app = wx.PySimpleApp()
frame = MyFrame(None)
frame.Show(True)
app.MainLoop()

1 个答案:

答案 0 :(得分:0)

呼叫

self.Refresh()
。否则系统不知道它应该重绘,所以它不会重绘......

(另外,一般来说,将coord作为成员变量而不是全局变量可能更好)

相关问题