简体   繁体   English

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

[英]Drawing a line in wxPython using mouse position

I'm trying to make program in wxPython, that will draw a line in a position in which I clicked on a window but it doesn't work and I actually don't know why. 我正在尝试使用wxPython编写程序,该操作会在我单击窗口的位置绘制一条线,但是它不起作用,我实际上也不知道为什么。 How could I write this, that it will work? 我怎么写这个,它会起作用?

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

Call 呼叫

self.Refresh()

at the end of OnLeftDown/OnRightDown. 在OnLeftDown / OnRightDown的末尾。 Otherwise the system does not know it should redraw so it won't redraw... 否则系统不知道应该重绘,因此不会重绘...

(also, generally speaking, it may be better to have coord as a member variable, not a global) (同样,一般来说,将coord作为成员变量而不是全局变量可能更好)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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