[Tutor] How to make object disappear?
Alan Gauld
alan.gauld at yahoo.co.uk
Mon May 9 12:34:33 EDT 2016
On 09/05/16 16:55, boB Stepp wrote:
>> class dot:
>> def __init__(self, canvas, color):
>> self.canvas = canvas
>> self.id = canvas.create_oval(15, 15, 30, 30, fill='Blue',
>> tags='dot1')
>>
>> this = dot(canvas, 'blue')
You create an instance of your class called this.
But you never refer to it again.
>> def ball(n, x, y):
>> canvas.move(n, x, y)
>>
>> def restart():
>> if (canvas.find_overlapping(x, y, x2, y2) == (1, 2)) or
>> (canvas.find_overlapping(x, y, x2, y2) == (1, 3)) or
>> (canvas.find_overlapping(x, y, x2, y2) == (1, 4)) or
>> (canvas.find_overlapping(x, y, x2, y2) == (1, 5)) or
>> (canvas.find_overlapping(x, y, x2, y2) == (1, 6)) == True:
>> canvas.delete('dot1')
Here you delete the shape that your object, this, drew on
the canvas but you do not delete the object. 'this' is
still there.
The normal way to do this kind of thing in a GUI program
is to have the class have a paint/draw method that makes
it visible and a hide/erase method that makes it invisible
(by drawing itself with the background colour). You probably
need a move() method too. You can then manipulate the "dot"
(although Ball is probably a more suitable name?) by
calling move() draw() and erase() on the object itself.
You might want an isOverlapping() method too, that simply
returns a boolean. That will hide all that horrible if/else
nastiness (or even the dictionary lookup if you adopt
Bob's (excellent) option.
You then wind up with something like
ball.move(x,y)
if ball.isOverlapping(X,Y,X1,Y1):
ball.erase()
else:
ball.draw()
Which is a lot more readable IMHO.
A more indirect solution to your problem would be to use
pyGame to build the game where sprites etc come as standard.
But pyGame itself does not of course come as standard... :-(
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list