[Tutor] [Fwd: self-modification]

Alan Gauld alan.gauld at freenet.co.uk
Mon Aug 21 17:47:31 CEST 2006


> I forgot the most important thing: the attachment.

OK, Here is my annotated version. not sure if it
will solve your problem though...

#############################

#!/usr/bin/python

# In this program I wanted to write the event <B1-Motion>
> on my own, combining <Button-1>, <Motion> and <ButtonRelease-1>

from Tkinter import *

def handler(event):
  if buttonpressed == 1 :
     #if the mousebutton is pressed and moved, circles should appear
    can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, 
fill="orange")
  lab.config(text='buttonpressed=' + str(buttonpressed) )

[AG] First point, using global variables like this is considered
[AG] bad practice, better to pass the canvas and label as a
[AG] parameter - or better still make the GUI a class and refer
[AG] to the attributes.within the methods

[AG] Also you are using buttonpressed as a boolean flag,
[AG]  so why not use boolean values - True/False?
[AG] Then your test just becomes

[AG] if buttonpressed: ...


def press(event):
     buttonpressed=1
     lab2.config(text=buttonpressed)

[AG]  use True here instead of 1 and you will also need to
[AG] declare it as global, otherwise you are simply creating
[AG] a local variable inside the function which then gets
[AG] thrown away - that might be why the behaviour isn't
[AG] as expected, global buttonpressed is always zero!

[AG] pass a string to the ttext attribute - I assume you want to
[AG] display the string 'button pressed', rather
[AG] than the rather cryptic number 1?

def release(event):
   buttonpressed=0

buttonpressed = False here..

   lab2.config(text=buttonpressed)

[AG] As above.

r=5
#global buttonpressed
buttonpressed=0

root = Tk()
root.geometry('600x500+200+200')

[AG] Using a fixed geometry rather undermines
[AG] the operation of pack(). Its usually better to let
[AG] the Geometry Manager manage the geometry ;-)
[AG]  If the user resizes the window it will all go awry anyhow!

# both labels are used to check the status of the variable 
buttonpressed
lab = Label(root, text='cucc')
lab2 = Label(root, text='cucc2')

[AG] Not sure why you have two, and why you
[AG] change the values from cucc to a number later.

can = Canvas(root, width='500', height='400', bg='white')
can.bind("<Motion>",handler)
can.bind("<Button-1>",press)
can.bind("<ButtonRelease-1>",release)

lab.pack()
lab2.pack()
can.pack()

root.mainloop()

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 



More information about the Tutor mailing list