[Tutor] tkinter events: <B1-Motion>

Luke Paireepinart rabidpoobear at gmail.com
Mon Aug 21 21:41:50 CEST 2006


Zsiros Levente wrote:
> [snip code]
> *def* handler(event):
> 	*if* buttonpressed == 1 :
> 		/#if the mousebutton is pressed and moved, circles should appear, but they do not/
> 		can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
> 	lab.config(text='buttonpressed=' + str(buttonpressed) )
>
> *def* press(event):
> 	buttonpressed=1
> 	lab2.config(text=buttonpressed)
> 	
> *def* release(event):
> 	buttonpressed=0
> 	lab2.config(text=buttonpressed)	
> [snip code]
> /#global buttonpressed/
> buttonpressed=0

I think you're misunderstanding what global variables are.

Take the following example:

#--- code
a = 0
def b():
    print a
b()

#--- output
0
#---
the function 'b' can see the variable 'a'. ok so far.

now take this example.

#--- code
a = 0
def b():
    a = 1
    print a
b()
print a

#--- output
1
0
#---
in this case, 'a' is assigned to, but it's a local variable called 'a' 
and not the one I think you expect it to assign to.
so after 'b' is done the value of the 'a' outside of the scope of the 
function is still 0.
in your press and release events you assign values to 'buttonpressed' 
before you use them,
and because of this, the same thing happens as in our second example: a 
local variable named
'buttonpressed' is created with the value 0 or 1 assigned to it 
(depending on the function you're in.)
that works fine, and it sets the label's text value accordingly.  But, 
since it's a local variable and the
functions aren't actually modifying the global 'buttonpressed', the 
'buttonpressed' that you're checking for
in your 'handler' function is always going to be 0.  That's why your 
oval code is never drawn.

Rather than messing with global variables, which are for the most part 
evil creatures,
as we've witnessed so far here, I'd recommend using a class.
I wrote the class I would use for you so you can see it.
It's commented, but if you need any more help than the comments feel 
free to write me back.
Just be sure to use the reply-all button so the whole list can see the 
response.
-Luke
(note: code attached)

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: test.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060821/cbddba30/attachment.pot 


More information about the Tutor mailing list