Python Forum
use classes in tkinter canvas
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
use classes in tkinter canvas
#1
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()
Reply
#2
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()
Reply
#3
Thank you very much Larz60+
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter & Canvas Peter_Emp1 5 407 Mar-24-2024, 07:40 PM
Last Post: deanhystad
  how to positon a tkinter canvas Tyrel 3 1,927 Dec-11-2020, 03:05 PM
Last Post: deanhystad
  Using classes? Can I just use classes to structure code? muteboy 5 5,065 Nov-01-2017, 04:20 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020