如何在tkinter画布中旋转椭圆?

3

我有一个简单的椭圆形(红色),我想要旋转这个椭圆形。 以下代码只返回扁平化的椭圆形(蓝色),但它并没有旋转: import tkinter as tk import numpy as np import math

def rotate(points, angle):
    new_points = list(points)
    rad = angle * (math.pi/180)
    cos_val = math.cos(rad)
    sin_val = math.sin(rad)
    for coords in new_points:
        x_val =  coords[0] 
        y_val = coords[1]
        coords[0] = x_val * cos_val - y_val * sin_val
        coords[1] = x_val * sin_val + y_val * cos_val
    return new_points

window = tk.Tk()
window.geometry("500x300")
canvas = tk.Canvas(window, height=300, width=500)
canvas.grid(row=0, column=0, sticky='w')

# draw ellipse 
size=80
x0,y0=100,100
width,height=0.25*size,0.5*size
x1,y1=x0+width,y0+height
xc=x0+width/2
yc=y0+height/2
ellipse = canvas.create_oval([x0, y0, x1,y1],fill='blue')

#draw rotated ellipse
coord1=canvas.coords(ellipse)
points=[[coord1[0],coord1[1]],[coord1[2],coord1[3]]]
point2=rotate(points,30)
coord2 = [item for sublist in point2 for item in sublist]
ellipse2 = canvas.create_oval(coord2,fill='red')

window.mainloop ()

这是结果:

red and blue ellipse. The blue one is supposed to be rotated

红色椭圆应该被旋转30度,但实际上它只是被压扁了。
问题:如何在tkinter画布中旋转椭圆?
注:
- 我使用的是Python 3.6 - 我查看了类似问题的stackoverflow,但没有正确的答案。 - 不同于我们可以简单地旋转每个顶点的多边形,椭圆没有顶点。

创建并绘制椭圆形的多边形,并旋转点: https://mail.python.org/pipermail/python-list/2000-December/022013.html - xaedes
2个回答

1
tkinter画布中的oval对象不能像oval一样旋转。
如果你查看文档,比如effbot.org,你会发现一些对象是通过第一个position参数创建的(一个单一的点,比如text),一些是通过bbox参数创建的(两个点,比如rectangleoval),还有一些是通过coords参数创建的(可变的,两个或多个点,比如linepolygon)。
你可以通过(1)计算新的坐标和(2)使用coords()方法更新对象的坐标来旋转coords对象。
对于其他对象,除了支持angle属性的text对象之外,你就没有办法了,你可以使用itemconfig(item, angle=new_angle)来设置它。
但是不要失去希望。您可以将矩形或椭圆转换为多边形(通过创建一个新的多边形来替换旧的bbox项,然后您将能够旋转新的项目)。对于矩形,这很容易。对于椭圆,它更加棘手,因为您必须使用许多多边形坐标来模拟椭圆以使其看起来好看。

0

我知道有两种方法:1)绘制椭圆边缘上的每个点。网页上有展示如何计算所有点的页面。2)将其保存为图像,使用tkinter的PIL库旋转图像。


你的意思是说,使用tkinter没有直接旋转椭圆的方法吗? - Hajar
@Hajar 正确。在画布上无法旋转“椭圆形”。请参阅我的答案以获取解释。 - GaryMBloom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接