在Tkinter中绘制圆(Python) [英] Draw circle in Tkinter (Python)
问题描述
通常在create_oval
方法上在tkinter Canvas
上绘制圆.但是,提供边界框通常是考虑绘制圆的一种令人困惑的方法.为其提供快捷方式并不是特别困难,但是我找不到其他人在做类似的事情,因此我将其发布,以希望其他人会发现它有用.
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.
推荐答案
这是一个称为猴子修补"的技巧,实际上我们在Tkinter
类Canvas
中添加了一个成员.下面是一个功能齐全的程序(Python 2.7),其中的第三段值得关注.将其添加到代码中,您就可以像对待内置方法一样对待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
class Canvas
. Below is a fully-functioning program (Python 2.7), 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
.
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()
结果:
这篇关于在Tkinter中绘制圆(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!