创建椭圆形Python Tkinter画布

2024-04-26 21:26:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python tkinter创建这个形状: enter image description here

但我只能选择

canvas.create_polygon
canvas.create_line
canvas.create_arc
canvas.create_oval

以上这些选项都不能生成这种形状。我可以用这些选项创建这个形状吗?在


Tags: tkinter选项createlinecanvas形状polygonarc
3条回答

create_arc方法就是您想要使用的方法。它以三种不同样式之一创建一个弧,由style参数指定。这是official tcl/tk documentation描述style选项的方式:

If type is pieslice (the default) then the arc's region is defined by a section of the oval's perimeter plus two line segments, one between the center of the oval and each end of the perimeter section. If type is chord then the arc's region is defined by a section of the oval's perimeter plus a single line segment connecting the two end points of the perimeter section. If type is arc then the arc's region consists of a section of the perimeter alone. In this last case the fill option is ignored.

下面是三种风格的一个例子:

import tkinter as tk

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

canvas.create_arc(0, 20, 100, 120, outline="red", style="pieslice")
canvas.create_arc(80, 20, 180, 120, outline="red", style="chord")
canvas.create_arc(160, 20, 260, 120, outline="red", style="arc")
root.mainloop()

screenshot

我想这就是你要找的。在

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

coord = 10, 50, 240, 210
arc = canvas.create_arc(coord, start=30, extent=120, style=tk.ARC, width=3)

root.mainloop()

enter image description here

正如@martineau所说,create_arc()是一种方法,但是理解tkinter的create_oval()是至关重要的,因为弧是椭圆的一部分:

import tkinter as tk

WINDOW_WIDTH, WINDOW_HEIGHT = 600, 300
OVAL_WIDTH, OVAL_HEIGHT = 576, 290

# (x0, y0, x1, y1) rectangle for oval
BOUNDS = ( \
    (WINDOW_WIDTH - OVAL_WIDTH) / 2, \
    (WINDOW_HEIGHT - OVAL_HEIGHT) / 2, \
    3*WINDOW_WIDTH/2 - OVAL_WIDTH/2, \
    3*WINDOW_HEIGHT/2 - OVAL_HEIGHT/2 \
)

root = tk.Tk()

canvas = tk.Canvas(root, width=WINDOW_WIDTH+20, height=WINDOW_HEIGHT+20)  # +20 for window "chrome"
canvas.pack()

rectangle = canvas.create_rectangle(*BOUNDS, outline="blue")  # just for illustration
oval = canvas.create_oval(*BOUNDS, outline="red")  # just for illustration
arc = canvas.create_arc(*BOUNDS, start=30, extent=120, style=tk.ARC, width=3)

root.after(3000, canvas.delete, rectangle)  # remove rectangle illustration
root.after(6000, canvas.delete, oval)  # remove oval illustration

root.mainloop()

When I have used Arc, it creates a line at the bottom as an outline to the arc - how can I get rid of this?

上面的style=tk.ARC负责处理这个问题默认是一个饼图切片。在

enter image description here

这段弧的端点如何终止与您的插图不一样。据我所知,tkinter的capstylejoinstyle选项对arc不可用。在

相关问题 更多 >