如何使Tkinter画布对象绕圆运动

时间:2019-10-06 14:44:31

标签: python tkinter

我有一个画布创建的图像:

在画布上,我画了一个圆圈:

产生该圆的代码:

def create_circle(x, y, r, canvasName): #center coordinates, radius
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return canvasName.create_oval(x0, y0, x1, y1, outline='red')
create_circle(100, 100, 50, canvas)

我想获得画布创建的图像,以每个像素精确地跟随画布绘制的圆圈(绕圆圈)。这怎么可能?

详细说明一下,这是我希望画布图像执行的演示:

https://i.gyazo.com/8218fe1c82008f2ed034a78b46f787e6.mp4

1 个答案:

答案 0 :(得分:1)

您可以使用root.after发送定期呼叫来更改图像的坐标。之后,只需计算每次调用中图像的新的x,y位置即可。

import tkinter as tk
from math import cos, sin, radians

root = tk.Tk()
root.geometry("500x500")

canvas = tk.Canvas(root, background="black")
canvas.pack(fill="both",expand=True)

image = tk.PhotoImage(file="plane.png").subsample(4,4)

def create_circle(x, y, r, canvasName):
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return canvasName.create_oval(x0, y0, x1, y1, outline='red')

def move(angle):
    if angle >=360:
        angle = 0
    x = 200 * cos(radians(angle))
    y = 200 * sin(radians(angle))
    angle+=1
    canvas.coords(plane, 250+x, 250+y)
    root.after(10, move, angle)

create_circle(250, 250, 200, canvas)
plane = canvas.create_image(450,250,image=image)

root.after(10, move, 0)

root.mainloop()

enter image description here