Python Forum
use classes in tkinter canvas - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: use classes in tkinter canvas (/thread-15151.html)



use classes in tkinter canvas - fardin - Jan-06-2019

I am trying to use classes to create ovals(circles) in canvas. I am a beginner and came with the following code. But the ball does not show and it does not move. I placed prints in between codes to see which codes get executed. Can someone tell me how I could fix this. Thanks

from tkinter import  *
import random
import time
tk =Tk()
tk.title("classy collision detection")
width = 700
height = 500
x1, y1 = 10, 10
x2, y2 = 60, 60
canvas = Canvas(tk, width=width,  height=height, bg='pink')
canvas.pack()
xspeed = 10
yspeed = 10


class Ball:
    def __init__(self, ball, colors):
        self.ball = ball  
        self.colors = random.choice(["red", "blue", "green", \
                                      "yellow", "brown", "cyan"])
        self.colors.pack()
        ball = canvas.create_oval(x1, y1, x2, y2, fill = colors)
        ball.pack()
        print("y")
    def move_ball(self):
            print("s")
            canvas.move(ball, xspeed, yspeed)
            print("h")
move = Ball.move_ball
move
print("k")
tk.update()
time.sleep(0.05)
canvas.mainloop()



RE: use classes in tkinter canvas - Larz60+ - Jan-06-2019

Forgive me for cleaning up a bit:
from tkinter import  *
import random
import time

 
class Ball:
    def __init__(self, parent):
        self.parent = parent
        self.parent.title("classy collision detection")

        self.canvas = Canvas(parent, width=700,  height=500, bg='pink')
        self.canvas.pack()
        self.xspeed, self.yspeed = 10, 10
        self.ball = self.add_ball()
        for x in range(20):
            self.move_ball()
            self.parent.update()
            time.sleep(0.05)

    def add_ball(self):
        x1, y1 = 10, 10
        x2, y2 = 60, 60
        colors = random.choice(["red", "blue", "green", 
                                "yellow", "brown", "cyan"])
        ball = self.canvas.create_oval(x1, y1, x2, y2, fill = colors)
        return ball

    def move_ball(self):
        self.canvas.move(self.ball, self.xspeed, self.yspeed)

def main():
    root = Tk()
    ball = Ball(root)
    root.mainloop()

if __name__ == '__main__':
    main()



RE: use classes in tkinter canvas - fardin - Jan-06-2019

Thank you very much Larz60+