27

在 a 上画一个圆tkinter Canvas通常是通过该create_oval方法完成的。但是,提供边界框通常是考虑绘制圆的一种令人困惑的方式。想出一个快捷方式并不是特别困难,但是我找不到其他人在做类似的事情,所以我会发布它,希望其他人觉得它有用。

4

2 回答 2

48

这是一个称为猴子补丁的技巧,我们实际上将成员添加到tkinter/TkinterCanvas。下面是一个功能齐全的程序(Python 2.7 和 3.x),其中第三段很有趣。将其添加到您的代码中,您可以将tk.Canvas.create_circle(x, y, r, options...)其视为内置方法,其中选项与create_oval. create_arc我们为(第四段)做了类似的事情,并提供了指定end角度而不是角度的选项extent

try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk  # Python 2

root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200, borderwidth=0, highlightthickness=0,
                   bg="black")
canvas.grid()

def _create_circle(self, x, y, r, **kwargs):
    return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.create_circle = _create_circle

def _create_circle_arc(self, x, y, r, **kwargs):
    if "start" in kwargs and "end" in kwargs:
        kwargs["extent"] = kwargs["end"] - kwargs["start"]
        del kwargs["end"]
    return self.create_arc(x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.create_circle_arc = _create_circle_arc

canvas.create_circle(100, 120, 50, fill="blue", outline="#DDD", width=4)
canvas.create_circle_arc(100, 120, 48, fill="green", outline="", start=45, end=140)
canvas.create_circle_arc(100, 120, 48, fill="green", outline="", start=275, end=305)
canvas.create_circle_arc(100, 120, 45, style="arc", outline="white", width=6,
                         start=270-25, end=270+25)
canvas.create_circle(150, 40, 20, fill="#BBB", outline="")

root.title("Circles and Arcs")
root.mainloop()

结果:

代码结果

于 2013-08-01T04:19:40.140 回答
15

更简单的解决方案:

from tkinter import *
root = Tk()
myCanvas = Canvas(root)
myCanvas.pack()

def create_circle(x, y, r, canvasName): #center coordinates, radius
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return canvasName.create_oval(x0, y0, x1, y1)

create_circle(100, 100, 20, myCanvas)
create_circle(50, 25, 10, myCanvas)
root.mainloop()
于 2019-01-04T13:01:05.727 回答