且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用 tkinter 画圆的更简单方法?

更新时间:2023-11-28 21:20:04

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

Here's a trick known as monkey patching where we actually add a member to the tkinter/Tkinter class Canvas. Below is a fully-functioning program (Python 2.7 and 3.x), of which the third paragraph is of interest. Add it to your code and you can treat tk.Canvas.create_circle(x, y, r, options...) as you would a builtin method, where the options are the same as create_oval. We do something similar for create_arc (fourth paragraph), and give the option to specify an end angle instead of an 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()

结果: