鼠标绘图不起作用

mouse drawing does not work

我尝试将允许用户在按下鼠标按钮后绘制的 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()

没有 error/warning 被触发,但是 canvas 没有任何反应。我错过了什么?显然条件 if self.xold is not None and self.yold is not None: 永远不会满足。

您切换了 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