I've tried many things and found out that
line19:if self.position[3]>=self.canvas_height:
There is something wrong with
I changed self.canvas_height
to 500 and it worked, but it's out of line with what I really want to do.
I just want to use winfo_height
to solve this problem.
Another thing we know is that if you print self.canvas_height
, you get 1.Why does it say 1 instead of 500?
Q1. How do I move the red ball up and down?
Q2. Why print self.canvas_height
to get 1?Why does Canvas already write height=500
so it becomes 1?
If Q2 can be solved, I think Q1 can be solved.Thank you for your understanding.
import tkinter
import time
Class Ball:
def__init__(self, canvas, color):
self.canvas=canvas
self.id=self.canvas.create_oval (10, 10, 25, 25, fill=color)
self.canvas.move (self.id, 250, 150)
self.canvas_height=self.canvas.winfo_height()
self.x = 0
self.y = 1
print(self.canvas_height)
def draw(self):
self.canvas.move (self.id, self.x, self.y)
self.position = self.canvas.coords (self.id)
if self.position[1]<=0:
self.y = 1
if self.position[3]>=self.canvas_height:
self.y=-1
root=tkinter.Tk()
root.minsize (width=500, height=500)
root.resizable(0,0)
canvas=tkinter.Canvas (width=500, height=500)
canvas.place(x=0,y=0)
ball = Ball (canvas, "red")
while True:
ball.draw()
canvas.update()
time.sleep(0.01)
root.mainloop()
You must run self.canvas.update() immediately before self.canvas_height=self.canvas.winfo_height() (widget geometry configuration is performed to determine properties such as height).
As metropolis commented, when self.canvas_height=self.canvas.winfo_height()
was inserted just before self.canvas.update()
, the red ball now reflects up and down the window.
import tkinter
import time
Class Ball:
def__init__(self, canvas, color):
self.canvas=canvas
self.id=self.canvas.create_oval (10, 10, 25, 25, fill=color)
self.canvas.move (self.id, 250, 150)
self.canvas.update()
self.canvas_height=self.canvas.winfo_height()
self.x = 0
self.y = 1
print(self.canvas_height)
def draw(self):
self.canvas.move (self.id, self.x, self.y)
self.position = self.canvas.coords (self.id)
if self.position[1]<=0:
self.y = 1
if self.position[3]>=self.canvas_height:
self.y=-1
root=tkinter.Tk()
root.minsize (width=500, height=500)
root.resizable(0,0)
canvas=tkinter.Canvas (width=500, height=500)
canvas.place(x=0,y=0)
ball = Ball (canvas, "red")
while True:
ball.draw()
canvas.update()
time.sleep(0.01)
root.mainloop()
© 2025 OneMinuteCode. All rights reserved.