Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

python - Simpler way to draw a circle with tkinter?

Drawing a circle on a tkinter Canvas is usually done by the create_oval method. However, supplying the bounding box is often a confusing way to think about drawing a circle. It's not particularly difficult to come up with a shortcut for it, but I couldn't find anyone else doing something similar, so I'll post it in the hopes someone else finds it useful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Result:

result of code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...