[Tutor] click and line
Shi Mu
samrobertsmith at gmail.com
Mon Nov 7 04:52:06 CET 2005
it works now.
from Tkinter import *
root = Tk()
c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
frame = c
lastX=""
lastY=""
def click(event):
global lastX, lastY
if lastX != "":
c.create_line(lastX,lastY,event.x,event.y,fill="white")
lastX = event.x
lastY = event.y
c.bind('<Button-1>',click)
c.pack()
root.mainloop()
On 11/6/05, Shi Mu <samrobertsmith at gmail.com> wrote:
> based on the following rewritten code, why the lines still can not be
> drawn? (there is no error report and the canvas appears).
>
> from Tkinter import *
>
> root = Tk()
>
> c = Canvas(root, bg='#0e2e0e', height=500, width=1000)
>
> lastX=""
> lastY=""
> def click(event):
> global lastX, lastY
> if lastX != "":
> c.create_line(lastX,lastY,event.x,event.y,fill="white")
> lastX = event.x
> lastY = event.y
>
> frame = c
> c.bind('<Button-1>',click)
>
> c.pack()
>
> root.mainloop()
>
> On 11/6/05, Danny Yoo <dyoo at hkn.eecs.berkeley.edu> wrote:
> >
> > Hi Shi Mu,
> >
> > Let's look at click():
> >
> > ##########################
> > def click(event):
> > print event.x, event.y
> > m1=event.x
> > n1=event.y
> > ##########################
> >
> > By default, variable names in functions are local. Do you know about
> > local vs global variables? The assignments to m1 and n1 won't be
> > remembered once we come out of the click() function.
> >
> >
> > It sounds like you want a function-like thing that remembers the very last
> > event we passed to it before. One way to do this is to use globals,
> > because globals last beyond function calls.
> >
> > For example:
> >
> > ######
> > >>> n = None
> > >>> def lastNumber(x):
> > ... global n
> > ... print "I last saw", n
> > ... n = x
> > ...
> > >>> lastNumber(42)
> > I last saw None
> > >>> lastNumber(17)
> > I last saw 42
> > >>> lastNumber(3)
> > I last saw 17
> > ######
> >
> > So for something very simple, using a global will probably be easiest.
> >
> >
> > However, there are other approaches that don't use globals. One that fits
> > Python's model well is to use a class instance, since instances can store
> > state:
> >
> > ######
> > >>> class LastNumber:
> > ... def __init__(self):
> > ... self.n = None
> > ... def getAndSet(self, x):
> > ... value = self.n
> > ... self.n = x
> > ... return value
> > ...
> > >>> last = LastNumber()
> > >>> last.getAndSet(42)
> > >>> last.getAndSet(3)
> > 42
> > >>> last.getAndSet(7)
> > 3
> > >>> last.getAndSet(9)
> > 7
> > ######
> >
> >
> > Does this make sense? Please feel free to ask questions here.
> >
> >
>
More information about the Tutor
mailing list