在Tkinter中绘制圆圈(Python)

时间:2013-08-01 04:19:40

标签: python tkinter geometry

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

2 个答案:

答案 0 :(得分:37)

这是一个称为“猴子修补”的技巧,我们实际上将一个成员添加到TkinterCanvas。下面是一个功能齐全的程序(Python 2.7),其中第三段是有意义的。将其添加到您的代码中,您可以像处理内置方法一样处理tk.Canvas.create_circle(x, y, r, options...),其中选项与create_oval相同。我们对create_arc(第四段)执行类似操作,并提供指定end角度而非extent的选项。

import Tkinter as tk

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.wm_title("Circles and Arcs")
root.mainloop()

结果:

result of code

答案 1 :(得分:1)

更简单的解决方案:

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()