0

I'm just starting making simple python GUIs. I was working on this one right here and when I run it the rectangle is static. Is there any fixes that would make the rectangle move 50 px horizontally every second? I've been working on trying to fix it but haven't had any success.

from tkinter import *
import time

rectMove = True

class rectMove():
    def __init__(self):
        root = Tk()
        frame = Frame(root, width=500, height=500)
        frame.grid()
        canvas = Canvas(frame, width=500, height=500)
        canvas.grid()
        firstX = 50
        firstY = 50
        secondX = 100
        secondY = 100
        rectangle = canvas.create_rectangle(firstX, firstY, secondX, secondY, fill="Black")
        while rectMove is True:
            rectangle.destroy()
            time.sleep(1)
            firstX += 50
            secondX += 50
            rectangle = canvas.create_rectangle(firstX, firstY, secondX, secondY, fill="Black")
        root.mainloop()

rectMove = rectMove()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Andy Kim
  • 21
  • 2
  • 1
    Possible duplicate of [Moving balls in Tkinter Canvas](https://stackoverflow.com/questions/25430786/moving-balls-in-tkinter-canvas) – Alan Hoover Jan 22 '18 at 02:39

1 Answers1

0

Your first problem is that you have a global variable named rectMove and you also have a class named rectMove. The class definition hides the global variable. This line: while rectMove is True: means "loop if the variable rectMove is the boolean variable True", which is false since rectMove isn't the variable True, it's a class. Therefore your loop doesn't execute at all.

What you probably want is something more like while True: but this simple change will expose other problems.

The first line in the loop, rectangle.destroy() raises an exception. The function you probably want is canvas.delete(rectangle). After you fix this and run the program, you won't see anything at all. That's because the while loop is infinite. Your program will just sit there forever.

Tk programs are event-driven. To make a timing loop is not simple. You need to use the function:

w.after(delay_ms, callback=None, *args)

Requests Tkinter to call function callback with arguments args after a delay of at least delay_ms milliseconds

These docs are from http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/universal.html

Instead of writing a simple while loop you need to write a callback function that erases and redraws the rectangle, then calls w.after again to repeat the process.

Paul Cornelius
  • 9,245
  • 1
  • 15
  • 24