(Tkinter) How run an animation after put the object? - python

I'm trying to learn tkinter, and I've found an animation of a ball (in this website).
I tried to modificate it to a ball that could be placed with the mouse. Until now I've done that first part, but I don't know how to add the movement. I suposse that the canvas need to be run before the code of the animation to obtain the ball coordinates.
import tkinter
import time
animation_window_width=800
animation_window_height=600
animation_ball_radius = 30
animation_ball_min_movement = 5
animation_refresh_seconds = 0.01
def animate_ball(window, canvas, xinc, yinc, ball):
while True:
canvas.move(ball,xinc,yinc)
window.update()
time.sleep(animation_refresh_seconds)
ball_pos = canvas.coords(ball)
xl,yl,xr,yr = ball_pos
if xl < abs(xinc) or xr > animation_window_width-abs(xinc):
xinc = -xinc
if yl < abs(yinc) or yr > animation_window_height-abs(yinc):
yinc = -yinc
def position_ball(event):
ball = canvas.create_oval(event.x-animation_ball_radius,
event.y-animation_ball_radius,
event.x+animation_ball_radius,
event.y+animation_ball_radius,
fill="blue", outline="white", width=4)
window = tkinter.Tk()
window.title("Tkinter Animation Demo")
window.geometry(f'{animation_window_width}x{animation_window_height}')
canvas = tkinter.Canvas(window)
canvas.configure(bg="black")
canvas.pack(fill="both", expand=True)
ball=canvas.bind("<Button-1>", position_ball)
ball
#animate_ball(window, canvas, animation_ball_min_movement, animation_ball_min_movement, ball)

That is a really bad example. For most GUIs you should never use an infinite loop with sleep() in a GUI thread since it blocks GUI mainloop (pygame is a notable exception to this). Most GUIs, including tkinter, are "event-driven", and you need to use events to do things. The event I think you want is the mouse movement. The event will contain the mouse x, y position, so all that's left is to transfer that to the ball.
import tkinter
animation_window_width=800
animation_window_height=600
animation_ball_radius = 30
animation_ball_min_movement = 5
animation_refresh_seconds = 0.01
def place_ball(event):
canvas.unbind("<Motion>") # stop responding to motion
canvas.xinc = animation_ball_min_movement
canvas.yinc = animation_ball_min_movement
animate_ball()
def locate_ball(event):
canvas.coords(ball,
event.x-animation_ball_radius,
event.y-animation_ball_radius,
event.x+animation_ball_radius,
event.y+animation_ball_radius)
# Create and animate ball in an infinite loop
def animate_ball(event=None):
canvas.move(ball,canvas.xinc,canvas.yinc) # move the ball
xl,yl,xr,yr = canvas.coords(ball) # get current coordinates
if xl < abs(canvas.xinc) or xr > animation_window_width-abs(canvas.xinc):
canvas.xinc = -canvas.xinc
if yl < abs(canvas.yinc) or yr > animation_window_height-abs(canvas.yinc):
canvas.yinc = -canvas.yinc
canvas.coords(ball, xl,yl,xr,yr) # set new coordinates
canvas.after(20, animate_ball) # set the loop event
window = tkinter.Tk()
window.title("Tkinter Animation Demo")
window.geometry(f'{animation_window_width}x{animation_window_height}')
canvas = tkinter.Canvas(window)
canvas.configure(bg="black")
canvas.pack(fill="both", expand=True)
ball = canvas.create_oval(0,0,0,0,fill="blue", outline="white", width=4)
canvas.bind('<Motion>', locate_ball)
canvas.bind('<Button-1>', place_ball)
window.mainloop()

Related

Using Python and Tkinter, How would I run code every loop of .mainloop()?

I have a program where I need to move an image object every time the mainloop() loops. I haven't tried doing much, mostly because I don't know where to start. I made a dummy version of my project that simulates the issue I'm having.
from tkinter import *
window = tk.Tk()
window.geometry('%ix%i+400+0' % (500, 600))
canvas = Canvas(window, width=500, height=600, bg='white')
canvas.pack()
w, x, y, z = 300, 300, 200, 200
x = canvas.create_rectangle(w, x, y, z)
def moveRectangle():
canvas.move(x, 10, 0)
# Run the moveRectangle function everytime the mainloop loops
window.mainloop()
To sum up my issue, I need to run mainloop as if it isn't a blocking function. Rather, either run it asynchronous, or maybe pause it and then run the function, though I don't think that's possible.
Anything helps
Thanks
Mainloop in tkinter doesn't loop through your code. It's looping through list of events. You can create an event by clicking buttons etc. Another way is that you can call commands like update() or update_idletasks(). Combinig that with after() can give you results you are looking for. So look up these in documentation, it will be helpful. Also you can read: understanding mainloop.
def moveRectangle():
canvas.move(x, 10, 0)
for i in range(20): # 20 moves 10px every 50ms
window.after(50, canvas.move(x, 10, 0))
window.update()
moveRectangle()
This little code above demonstrate how you could use mentioned commands to get your object move on screen.
I think there are ways to set up a custom mainloop() which could update your UI every time the loop runs but depending on what you want to do the more usual method is to use after. By arranging for the function called by after to call itself with after an effective loop can be created.
I've amended you code to bounce the rectangle as it reaches the sides of the canvas so it can show something as it runs indefinitely.
import tkinter as tk
WAIT = 10 # in milliseconds, can be zero
window = tk.Tk()
window.geometry('%ix%i+400+0' % (500, 600))
canvas = tk.Canvas(window, width=500, height=600, bg='white')
canvas.pack()
w, x, y, z = 300, 300, 200, 200
x = canvas.create_rectangle(w, x, y, z)
amount = 10
def direction( current ):
x0, y0, x1, y1 = canvas.bbox( x )
if x0 <= 0:
return 10 # Move rect right
elif x1 >= 500:
return -10 # Move rect left
else:
return current
def moveRectangle():
global amount
canvas.move(x, amount, 0)
window.update()
# Change Direction as the rectangle hits the edge of the canvas.
amount = direction( amount )
window.after( WAIT, moveRectangle )
# ms , function
# Loop implemented by moveRectangle calling itself.
window.after( 1000, moveRectangle )
# Wait 1 second before starting to move the rectangle.
window.mainloop()

How do I get mouse position with tkinter and turtle?

I am trying to make a program that lets me draw on a tkinter window using turtle. For some reason I cannot get the absolute mouse coordinates.
I have done root.winfo_pointerx() - root.winfo_rootx() (and vrootx).
I have also tried:
def mousePos(event):
x,y = event.x , event.y
return x,y
My code:
import turtle
import tkinter as tk
root = tk.Tk()
root.title("Draw!")
cv = tk.Canvas(root, width=500,height=500)
cv.focus_set()
cv.pack(side = tk.LEFT)
pen = turtle.RawTurtle(cv)
window = pen.getscreen()
def main():
window.setworldcoordinates(-500,-500,500,500)
window.bgcolor("white")
frame = tk.Frame(root)
frame.pack(side = tk.RIGHT,fill=tk.BOTH)
pointLabel = tk.Label(frame,text="Width")
pointLabel.pack()
def getPosition(event):
x = root.winfo_pointerx()-root.winfo_vrootx()
y = root.winfo_pointery()-root.winfo_vrooty()
pen.goto(x,y)
cv.bind("<Motion>", getPosition)
cv.pack
tk.mainloop()
pass
I want the cursor to be on top of the arrow, but instead it is always to the right and down. Also, when I move the mouse up, the arrow moves down, and vice versa.
Think hard about how you set the setworldcoordinate(). -500 - 500 means your world has 1,000 in size and window size is 500. Also, the mouse pointer offset from the window root - both absolute coordinates should be used. You mixed up the absolute coordinates - mouse pointer and vrootx which is in different scale so the distance of two makes no sense. Following code is probably closer to what you intended. Note that, I set the world coordinate to match the absolute coordinates of mouse pointer offset from the top/left corner of window.
import turtle
import tkinter as tk
root = tk.Tk()
root.title("Draw!")
cv = tk.Canvas(root, width=500,height=500)
cv.focus_set()
cv.pack(side = tk.LEFT)
pen = turtle.RawTurtle(cv)
window = pen.getscreen()
def main():
window.setworldcoordinates(0,500,500,0)
window.bgcolor("white")
frame = tk.Frame(root)
frame.pack(side = tk.RIGHT,fill=tk.BOTH)
pointLabel = tk.Label(frame,text="Width")
pointLabel.pack()
print(dir(root))
def getPosition(event):
x = root.winfo_pointerx()-root.winfo_rootx()
y = root.winfo_pointery()-root.winfo_rooty()
print(x, y)
pen.goto(x,y)
pass
cv.bind("<Motion>", getPosition)
cv.pack
tk.mainloop()
pass
if __name__ == "__main__":
main()
pass
You've got an issue working against you that isn't of your own making. The general rule is when in a turtle canvas, use turtle methods. But turtle doesn't have an inherent 'Motion' event type, so you were trying to use the raw Canvas one as a substitute. Thus the conflict.
An issue of your own making is that when you're inside a fast moving event handler, you need to disable the event hander as the first thing you do, reenabling on exit. Otherwise, events overlap and bad things happen. (Inadvertant recursions and other wierdness.)
I've rewritten your program below to work as I believe you intended. The fix is adding the missing turtle method so we can stay within the turtle domain:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen
from functools import partial
def onscreenmove(self, fun, add=None): # method missing from turtle.py
if fun is None:
self.cv.unbind('<Motion>')
else:
def eventfun(event):
fun(self.cv.canvasx(event.x) / self.xscale, -self.cv.canvasy(event.y) / self.yscale)
self.cv.bind('<Motion>', eventfun, add)
def getPosition(x, y):
screen.onscreenmove(None) # disable events inside handler
pen.setheading(pen.towards(x, y))
pen.goto(x, y)
screen.onscreenmove(getPosition) # reenable handler on exit
root = tk.Tk()
root.title("Draw!")
cv = tk.Canvas(root, width=500, height=500)
cv.focus_set()
cv.pack(side=tk.LEFT)
screen = TurtleScreen(cv)
screen.onscreenmove = partial(onscreenmove, screen) # install missing method
pen = RawTurtle(screen)
frame = tk.Frame(root)
frame.pack(side=tk.RIGHT, fill=tk.BOTH)
tk.Label(frame, text="Width").pack()
screen.onscreenmove(getPosition)
screen.mainloop()
Mouse position for Tkinter:
import Tkinter as tk
root = tk.Tk()
def motion(event):
x, y = event.x, event.y
print('{}, {}'.format(x, y))
root.bind('<Motion>', motion)
root.mainloop()
Mouse position for turtle:
canvas = turtle.getcanvas()
x, y = canvas.winfo_pointerx(), canvas.winfo_pointery()
Hope this helps.

Turtle in Tkinter creating multiple windows

I am attempting to create a quick turtle display using Tkinter, but some odd things are happening.
First two turtle windows are being created, (one blank, one with the turtles), secondly, any attempt of turning the tracer off is not working.
This might be a simple fix but at the moment I cannot find it.
Any help would be appreciated,
Below is the code:
import tkinter as tk
import turtle
window = tk.Tk()
window.title('Top 10\'s')
def loadingscreen():
canvas = tk.Canvas(master = window, width = 500, height = 500)
canvas.pack()
arc1 = turtle.RawTurtle(canvas)
arc2 = turtle.RawTurtle(canvas)
#clean up the turtles and release the window
def cleanup():
turtle.tracer(True)
arc1.ht()
arc2.ht()
turtle.done()
#animate the turtles
def moveTurtles(rangevar,radius,extent,decrease):
for distance in range(rangevar):
arc1.circle(-radius,extent = extent)
arc2.circle(-radius,extent = extent)
radius -= decrease
#Set the turtle
def setTurtle(turt,x,y,heading,pensize,color):
turt.pu()
turt.goto(x,y)
turt.pd()
turt.seth(heading)
turt.pensize(pensize)
turt.pencolor(color)
#draw on the canvas
def draw():
#set variables
rangevar = 200
radius = 200
decrease = 1
extent = 2
#setup and draw the outline
turtle.tracer(False)
setTurtle(arc1,0,200,0,40,'grey')
setTurtle(arc2,14,-165,180,40,'grey')
moveTurtles(rangevar,radius,extent,decrease)
#setup and animate the logo
turtle.tracer(True)
setTurtle(arc1,0,200,0,20,'black')
setTurtle(arc2,14,-165,180,20,'black')
moveTurtles(rangevar,radius,extent,decrease)
#main program
def main():
turtle.tracer(False)
arc1.speed(0)
arc2.speed(0)
draw()
cleanup()
if __name__ == "__main__":
try:
main()
except:
print("An error occurred!!")
loadingscreen()
Essentially I am creating a Tk window, then a canvas, then two turtles, and then animating these turtles
My guess is you're trying to call turtle screen methods without actually having a turtle screen. When turtle is embedded in tkinter like this, you can overlay a Canvas with a TurtleScreen instance which will provide some, but not all, of the screen features of the standalone turtle:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen
def cleanup():
""" hide the turtles """
arc1.hideturtle()
arc2.hideturtle()
def moveTurtles(rangevar, radius, extent, decrease):
""" animate the turtles """
for _ in range(rangevar):
arc1.circle(-radius, extent=extent)
arc2.circle(-radius, extent=extent)
radius -= decrease
def setTurtle(turtle, x, y, heading, pensize, color):
turtle.penup()
turtle.goto(x, y)
turtle.pendown()
turtle.setheading(heading)
turtle.pensize(pensize)
turtle.pencolor(color)
def draw():
# set variables
rangevar = 200
radius = 200
decrease = 1
extent = 2
screen.tracer(False) # turn off animation while drawing outline
# setup and draw the outline
setTurtle(arc1, 0, 200, 0, 40, 'grey')
setTurtle(arc2, 14, -165, 180, 40, 'grey')
moveTurtles(rangevar, radius, extent, decrease)
screen.tracer(True) # turn animation back on for the following
# setup and animate the logo
setTurtle(arc1, 0, 200, 0, 20, 'black')
setTurtle(arc2, 14, -165, 180, 20, 'black')
moveTurtles(rangevar, radius, extent, decrease)
# main program
window = tk.Tk()
window.title("Top 10's")
canvas = tk.Canvas(master=window, width=500, height=500)
canvas.pack()
screen = TurtleScreen(canvas)
arc1 = RawTurtle(screen)
arc1.speed('fastest')
arc2 = RawTurtle(screen)
arc2.speed('fastest')
draw()
cleanup()
Another suggestion: don't mess with tracer() until after everything else is working and then (re)read it's documentation carefully.
I just have the answer for the two windows that are being created: the one with the turtles is obvious, and the blank one is for the main root window that you define (window = tk.Tk()). If you want it not to appear at all, you can add the following line right after its definition:
window.withdraw()
I found this solution here and here.

Turtle freehand drawing

I'm working on a simple drawing program that combines Tkinter and Turtle modules.
I would like to add an option that the user can draw anything by just using mouse similar to pen widget on Paint. I tried many things, I could not figure out how l can do it.How can l make the turtle draw anything (like pen widget on Paint ) on canvas by using mouse
from tkinter import *
import turtle
sc=Tk()
sc.geometry("1000x1000+100+100")
fr4=Frame(sc,height=500,width=600,bd=4,bg="light green",takefocus="",relief=SUNKEN)
fr4.grid(row=2,column=2,sticky=(N,E,W,S))
#Canvas
canvas = Canvas(fr4,width=750, height=750)
canvas.pack()
#Turtle
turtle1=turtle.RawTurtle(canvas)
turtle1.color("blue")
turtle1.shape("turtle")
points=[]
spline=0
tag1="theline"
def point(event):
canvas.create_oval(event.x, event.y, event.x+1, event.y+1, fill="red")
points.append(event.x)
points.append(event.y)
return points
def canxy(event):
print (event.x, event.y)
def graph(event):
global theline
canvas.create_line(points, tags="theline")
def toggle(event):
global spline
if spline == 0:
canvas.itemconfigure(tag1, smooth=1)
spline = 1
elif spline == 1:
canvas.itemconfigure(tag1, smooth=0)
spline = 0
return spline
canvas.bind("<Button-1>", point)
canvas.bind("<Button-3>", graph)
canvas.bind("<Button-2>", toggle)
sc.mainloop()
The following code will let you freehand draw with the turtle. You'll need to integrate with the rest of your code:
import tkinter
import turtle
sc = tkinter.Tk()
sc.geometry("1000x1000+100+100")
fr4 = tkinter.Frame(sc, height=500, width=600, bd=4, bg="light green", takefocus="", relief=tkinter.SUNKEN)
fr4.grid(row=2, column=2, sticky=(tkinter.N, tkinter.E, tkinter.W, tkinter.S))
# Canvas
canvas = tkinter.Canvas(fr4, width=750, height=750)
canvas.pack()
# Turtle
turtle1 = turtle.RawTurtle(canvas)
turtle1.color("blue")
turtle1.shape("turtle")
def drag_handler(x, y):
turtle1.ondrag(None) # disable event inside event handler
turtle1.goto(x, y)
turtle1.ondrag(drag_handler) # reenable event on event handler exit
turtle1.ondrag(drag_handler)
sc.mainloop()

my tkinter window doesn't open up when I add the sleep() part

I am trying to make a ball go to one side of the screen turn around, then come back. Whenever I try running this program the tkinter window doesn't show up, but when i get rid of the sleep(0.5) part it shows up when the ball is already off the screen. Can someone tell my what I did wrong?
from tkinter import *
from time import sleep
window = Tk()
cWidth = 800
cHeight = 500
c = Canvas(window, width = cWidth, height = cHeight, bg='black')
c.pack()
x = 400
y = 250
ball = c.create_polygon(x, y, x, y+25, x+25, y+25, x+25,y, fill='yellow')
Ball_move = 10
for i in range(200):
c.move(ball, Ball_move, 0)
window.update
x += Ball_move
if x == cWidth:
Ball_move = -Ball_move
sleep(0.5)
window.mainloop()
In windows, Tkinter frame shows up only after you call mainloop(). In your case, the for loop might be blocking it. Keep the for loop in a function and then call that function using threads so that it won't block the main loop.

Categories

Resources