Jason
Jason

Reputation: 57

How to clear a window at runtime?

I am just learning Python. I have a program that will choose a random image each time you click the mouse!! How do I clear the window so images don't stack. I am sure I am asking this question wrong because google is no help :(

Thank you and here is the code:

from graphics import*
import random
import os

win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()

Upvotes: 0

Views: 353

Answers (1)

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

Based on the code at http://mcsp.wartburg.edu/zelle/python/graphics.py, the Image class has an undraw function. You can simply add image.undraw() with a check to make sure it's not None (as it would be for the first time in the loop:

img = None
win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    if img:
        img.undraw()
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()

(Note, change added based on cdlane's comment - initialize img to None so we don't get variable undefined.)

Upvotes: 1

Related Questions