鼠标绘图不起作用

时间:2015-05-05 16:08:42

标签: python python-2.7 tkinter

我尝试转换此code,允许用户在按下鼠标按钮后绘制到面向对象的对象:

from Tkinter import *

class Test:
   def __init__(self):
       self.b1="up"
       self.xold=None
       self.yold=None
   def test(self,obj):
       self.drawingArea=Canvas(obj)
       self.drawingArea.pack() 
       self.drawingArea.bind("<Motion>",self.motion)
       self.drawingArea.bind("<ButtonPress-1>",self.b1down)
       self.drawingArea.bind("<ButtonRelease-1>",self.b1up)
   def motion(self,event):
       self.b1="down"
   def b1up(self,event):
       self.b1="up"
       self.xold=None
       self.yold=None
   def b1down(self,event):
      if self.b1=="down":
           if self.xold is not None and self.yold is not None:
               event.widget.create_line(self.xold,self.yold,event.x,event.y,smooth=TRUE)
           self.xold=event.x
           self.yold=event.y


if __name__=="__main__":
   root=Tk()
   root.wm_title("Test")
   v=Test()
   v.test(root)
   root.mainloop()

没有触发错误/警告,但画布上没有任何反应。我错过了什么?显然条件if self.xold is not None and self.yold is not None:永远不会满足。

1 个答案:

答案 0 :(得分:2)

您切换了motionb1down功能。在<ButtonPress-1>事件中,应设置标记self.b1="down",并在<Motion>上进行绘图:

def b1down(self, event):
    self.b1 = "down"

def motion(self, event):
    if self.b1 == "down":
        if self.xold is not None and self.yold is not None:
            event.widget.create_line(self.xold, self.yold, event.x, event.y, smooth=TRUE)
        self.xold = event.x
        self.yold = event.y