gpt4 book ai didi

python - 如何在 tkinter Canvas 中旋转椭圆?

转载 作者:行者123 更新时间:2023-12-05 06:36:08 25 4
gpt4 key购买 nike

我有一个简单的椭圆(红色),我想旋转椭圆。以下代码仅返回展平椭圆(蓝色)但不旋转: 将 tkinter 导入为 tk 将 numpy 导入为 np 导入数学

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 canvas中旋转椭圆?

注意事项:

  • 我正在使用 python 3.6

  • 我在 similar question 上检查了 stackoverflow|并且没有正确答案。

  • 与我们可以简单地旋转每个顶点的多边形不同,椭圆没有顶点。

最佳答案

tkinter canvas 的 oval 项目不能作为 oval 旋转。

如果你查看文档,比如 effbot.org,你会看到一些项目是用第一个 position arg 创建的(一个点,比如 text ),有些带有 bbox arg(两点,如 rectangleoval),有些带有 coords(变量,两个或多个点,如 linepolygon)。

您可以使用 coords() 方法通过 (1) 计算新坐标和 (2) 使用新坐标更新项目来旋转 coords 项目。

对于其余的项目,你运气不好,除了 text 支持 angle 属性,你可以使用 itemconfig(item , 角度=new_angle)

但所有的希望都没有破灭。您可以将 rectangleoval 转换为 polygon(通过创建一个新的 polygon 来替换旧的 bbox item,然后你就可以旋转新的item了。使用rectangle,很简单。使用oval,就比较棘手了,因为您必须使用很多很多 polygon 坐标来模拟 oval 才能让它看起来不错。

关于python - 如何在 tkinter Canvas 中旋转椭圆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49269755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com