Home > database >  Can I set an exact location of an object using tkinter?
Can I set an exact location of an object using tkinter?

Time:04-05

Using Python3.7 I have created code that will move a ball from the top left corner to the bottom right corner. I am using coords to position the ball and move for the motion of the ball. However, I want the ball to start in a certin place. How can I set the position of the ball?

  1. I have tried using place function and I get the error: 'int' object has no attribute 'place'
  2. I tried using coords and I get the error: IndexError: list index out of range
  3. I have tried changing my create_oval code. It works for the size of the ball but not where it starts from.

The code here works with no errors. How and where should I have a line for the exact coordinates of where the ball will start.

import tkinter as tkr
import time
tk = tkr.Tk()
canvas = tkr.Canvas(tk, width=480, height=480)
canvas.grid()
ball = canvas.create_oval(10,10,20,20,fill="blue")
x = 1
y = 1
while True:
    canvas.move(ball,x,y)
    pos = canvas.coords(ball)
    if pos [3] >= 480 or pos[1] <=0:
        y = -y
    if pos[2] >= 480 or pos[0] <= 0:
        x = -x
    tk.update()
    time.sleep(0.0099)
    pass
tk.mainloop()

Also if I can get rid of the deprecation warning, that would be great as well.

CodePudding user response:

Here's how you do a loop like this within the confines of an event-driven UI framework. Each callback does one little bit of work, then goes back to the loop to wait for future events.

import tkinter as tk
import time
win = tk.Tk()
canvas = tk.Canvas(win, width=480, height=480)
canvas.grid()
x = 10
y = 10
dx = 1
dy = 1

def moveball():
    global x, dx
    global y, dy
    x  = dx
    y  = dy
    canvas.move(ball,dx,dy)
    if y >= 480 or y <=0:
        dy = -dy
    if x >= 480 or x <= 0:
        dx = -dx
    win.after( 10, moveball )

ball = canvas.create_oval(x,y,x 10,y 10,fill="blue")
win.after( 100, moveball )
win.mainloop()

You'll note that the ball doesn't change directions until after it's all the way off the edge of the screen. That's because we're tracking the upper left corner of the ball and not taking the size into account. That's an easy thing to fix.

CodePudding user response:

Used variables with the create_oval.

import tkinter as tkr
import time
tk = tkr.Tk()
canvas = tkr.Canvas(tk, width=480, height=480)
canvas.grid()
x = 47
y = 185
ball = canvas.create_oval(x,y,x 10,y 10,fill="blue")

dx = 1
dy = 1

while True:
    canvas.move(ball,dx,dy)
    pos = canvas.coords(ball)
    if pos [3] >= 480 or pos[1] <=0:
        dy = -dy
    if pos[2] >= 480 or pos[0] <= 0:
        dx = -dx
    tk.update()
    time.sleep(0.0099)
    pass
tk.mainloop()

Big thanks to Tim Roberts. I end up taking his coding advice and edit mine original code.

  • Related