Understanding Tkinter after ()

First of all, take a look at my previous topic: Tkinter understands mainloop

Following the recommendations from there, in GUI programming, you need to avoid endless loops at all costs, so that the widgets respond to user input.

Instead of using:

while 1:
    ball.draw()
    root.update()
    time.sleep(0.01)

I managed to use self.canvas.after(1, self.draw)inside my function draw().

So now my code looks like this:

# Testing skills in game programming

from Tkinter import *

root = Tk()
root.title("Python game testing")
root.resizable(0, 0)
root.wm_attributes("-topmost", 1)

canvas = Canvas(root, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
root.update()

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas
        self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
        self.canvas.move(self.id, 245, 100)

        self.canvas_height = canvas.winfo_height()
        self.x = 0
        self.y = -1

    def draw(self):
        self.canvas.move(self.id, self.x, self.y)

        pos = self.canvas.coords(self.id)
        if pos[1] <= 0:
            self.y = 1
        if pos[3] >= self.canvas_height:
            self.y = -1

        self.canvas.after(2, self.draw)


ball = Ball(canvas, "red")
ball.draw()

root.mainloop()

However, the time inside self.canvas.after()does not work properly ... If set to 1, it is very fast! If it is set to 10, 5 or even 2, it is too slow! I did not have this problem when using the above while loop in my code, as it time.sleep()worked as it should!


EDIT:

, Tkinter Windows 8.1 Windows 8.1, Ubuntu , .

+4
2

time.sleep , after() - . time.sleep(0.01) - , self.canvas.after(10, self.draw). (2, func) , (1, func) , (0.0005), (1, func) 1,5 , . , , .

0

() / , . , 2 , , 10... 25...

...
self.canvas.after(2, self.draw)
... # loop this after 2 ms.

, " ":

pos = self.canvas.coords(self.id)
    if pos[1] <= 0:
        self.y = 20
    if pos[3] >= self.canvas_height:
        self.y = -20

:

self.canvas.move(self.id, 245, 100)

. ,

0

All Articles