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:
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 , .