在Python tkinter中创建旋转椭圆形状(椭圆)的代码中出现“apply not defined”错误

icnyk63a  于 2023-02-26  发布在  Python
关注(0)|答案(1)|浏览(190)

寻找能够在Python tkinter画布上创建旋转椭圆(椭圆形)的Python代码,我在网上找到了一个解决方案,但代码的最后几行:

dict = {}
dict['outline'] = 'black'
dict['fill']   = 'yellow'
dict['smooth'] = 'true'

# use a polygon to draw an oval rotated 30 degrees anti-clockwise
apply(canvas.create_polygon, tuple(poly_oval(40,40, 200,300, rotation=30)), dict)

当我在Python 3.11中运行它时(代码是2000年的),出现了错误:

apply(canvas.create_polygon, tuple(poly_oval(40,40, 200,300, rotation=30)), dict)
    ^^^^^
NameError: name 'apply' is not defined

给出错误的代码行是做什么的?如何重写它以使它运行时没有错误?
完整代码可在线获取here

dnph8jn4

dnph8jn41#

apply()函数可以在2000年第三版的《Tcl and Tk实用编程》中找到,但是要得到旋转椭圆,你根本不需要它。所以如果你改变:

apply(canvas.create_polygon, tuple(poly_oval(40,40, 200,300, rotation=30)), dict)

致:

canvas.create_polygon(poly_oval(40,40, 200,300, rotation=30), dict)

它会画出一个漂亮的旋转椭圆

为了完整起见,下面的整个代码:

import tkinter
import math
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=400, height=400)

def poly_oval(x0,y0, x1,y1, steps=20, rotation=0):
    """return an oval as coordinates suitable for create_polygon"""

    # x0,y0,x1,y1 are as create_oval

    # rotation is in degrees anti-clockwise, convert to radians
    rotation = rotation * math.pi / 180.0

    # major and minor axes
    a = (x1 - x0) / 2.0
    b = (y1 - y0) / 2.0

    # center
    xc = x0 + a
    yc = y0 + b

    point_list = []

    # create the oval as a list of points
    for i in range(steps):

        # Calculate the angle for this step
        # 360 degrees == 2 pi radians
        theta = (math.pi * 2) * (float(i) / steps)

        x1 = a * math.cos(theta)
        y1 = b * math.sin(theta)

        # rotate x, y
        x = (x1 * math.cos(rotation)) + (y1 * math.sin(rotation))
        y = (y1 * math.cos(rotation)) - (x1 * math.sin(rotation))

        point_list.append(round(x + xc))
        point_list.append(round(y + yc))

    return point_list

dict = {}
dict['outline'] = 'black'
dict['fill']   = 'yellow'
dict['smooth'] = 'true'

# use a polygon to draw an oval rotated 30 degrees anti-clockwise
canvas.create_polygon(poly_oval(40,40, 200,300, rotation=30), dict)
canvas.pack()
root.mainloop()

相关问题