我不明白,如何在椭圆周围移动圆圈?椭圆坐标必须由用户输入,并且每次都会改变,我怎么办那个圆圈总是围绕椭圆?我知道我的代码是错误的,它只能绕圆移动,但我需要椭圆,这只是原型。
import tkinter as tk
from math import cos, sin, radians
root = tk.Tk()
root.geometry("1000x1000")
canvas = tk.Canvas(root, background="black")
canvas.pack(fill="both",expand=True)
image = tk.PhotoImage(file="unnamed.png").subsample(7,7)
x2= int(input('enter radius x :'))
y2= int(input('enter radius y:'))
def create_circle(x, y, r, canvasName):
x0 = x - r
y0 = y - r
x1 = x + r
y1 = y + r
return canvas.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(circle, x2+x, y2+y)
root.after(10, move, angle)
create_circle (x2,y2,200,canvas)
circle = canvas.create_image(200,100,image=image)
root.after(10, move, 0)
root.mainloop()
答案 0 :(得分:0)
没有内置的方法来实现这一点。所以,你必须自己计算。
tkinter 中的圆由 (x1, y1, x2, y2) 定义,即矩形(或正方形)。
这是一张图片,解释了如何在 tkinter 中绘制圆以及如何找到 (x, y)
上图中的θ是角度
这里的 (s, t)
分别由方程 (x2-x1)/2
和 (y2-y1)/2
定义
这是您之前代码的演示(在您编辑代码之前)。:
from tkinter import *
import math
x = 10
y = 10
a = 50
b = 50
t = 0
radius = 50 #radius around the circle
x_vel = 5
y_vel = 5
def move():
global x, y, x_vel, y_vel, t, radius
if x < 0:
x_vel = 5
if x > 700:
x_vel = -5
if y < 0:
y_vel = 5
if y > 700:
y_vel = -5
canvas1.move(circle, x_vel, y_vel)
rx, ry, rw, rh = canvas1.coords(circle)
rx1 = ((rw-rx)/2) +radius # gets the s of the main circle
ry1 = ((rh-ry)/2) +radius # gets the t of the main circle
cx = rx1*math.cos(t) + ry1*math.sin(t)
cy = -rx1*math.sin(t) + ry1*math.cos(t)
t += 1 # jump by how many degree
if t > 360:
t=0
canvas1.moveto(rect2, cx+x, cy+y)
x = rx
y = ry
window.after(33, move)
window = Tk()
window.geometry("1000x1000")
canvas1=Canvas(window, height = 1000, width= 1000)
canvas1.grid (row=0, column=0, sticky=W)
coord = [x, y, a, b ]
circle = canvas1.create_oval(coord, outline="red", fill="red")
x0= int(input("enter x center coord"))
y0= int(input("enter y center coord"))
coord = [x0, y0, y0, x0]
rect2 = canvas1.create_oval(coord, outline="Red", fill="")
move()
window.mainloop ()