[Tutor] how do i access object

Ketan Maheshwari kmaheshw at science.uva.nl
Wed Jan 3 22:10:38 CET 2007


Hi All
I have this code from the web that I modified according to y 
requirements. It has a class called Circle. Then there are a few objects 
of this class created using a constructor. The constructor essentially 
creates the circles and the update mathod makes them move randomly. 
However, at each updation, I want to access each circle to know its 
coordinates. At the moment I am not able to do that. I am sure it should 
be easy to do. Could anyone help me please.

Thanks,
k.

Code follows:
******************code starts here***************************
from Tkinter import *
import time
import random
class Circle:
    def __init__(self, canvas, xy, ink, delta):
        self.canvas = canvas
        self.id = self.canvas.create_oval(
            -15, -15,
            15, 15,
            fill=ink
            )
       
        self.canvas.move(self.id, xy[0], xy[1])
        self.delta = delta
        self.start = self.move
     
    def __call__(self):
            return self.start # get things going
    def move(self):
        rand=random.randint(1,4)
       
        if rand==1:
            xy = self.canvas.coords(self.id)
            #print xy
            if xy[2] >= self.canvas.winfo_width():
                self.canvas.move(self.id,-self.delta,0)
            self.canvas.move(self.id,self.delta,0)
        elif rand==2:
            xy = self.canvas.coords(self.id)
            if xy[0] <= 0:
                self.canvas.move(self.id,self.delta,0)
            self.canvas.move(self.id,-self.delta,0)
        elif rand==3:
            xy = self.canvas.coords(self.id)
            if xy[1] <= 0:
                self.canvas.move(self.id,0,self.delta)
            self.canvas.move(self.id,0,-self.delta)
        else:
            xy = self.canvas.coords(self.id)
            if xy[3] >= self.canvas.winfo_height():
                self.canvas.move(self.id,0,-self.delta)
            self.canvas.move(self.id,0,self.delta)
        return self.move

       
   
root = Tk()
root.title("Circles")
root.resizable(0, 0)

frame = Frame(root, bd=5, relief=SUNKEN)
frame.pack()

canvas = Canvas(frame, width=200, height=200, bd=0, highlightthickness=0)
canvas.pack()

items = [
    Circle(canvas, (60, 70), "blue", 1),
    Circle(canvas, (100, 120), "green", 1),
    ]

root.update() # fix geometry

# loop over items

try:
    while 1:
        for i in range(len(items)):
            items[i] = items[i]()
            root.update_idletasks() # redraw
        root.update() # process events
        time.sleep(0.02)
except TclError:
    pass # to avoid errors when the window is closed

*************************************code ends 
here******************************


More information about the Tutor mailing list