我遇到了一个有趣的问题(How to make a tkinter canvas rectangle with rounded corners?),与在Tkinter中创建圆形矩形有关,特别是Francisco Gomes的回答(稍加修改):
def roundPolygon(x, y, sharpness):
# The sharpness here is just how close the sub-points
# are going to be to the vertex. The more the sharpness,
# the more the sub-points will be closer to the vertex.
# (This is not normalized)
if sharpness < 2:
sharpness = 2
ratioMultiplier = sharpness - 1
ratioDividend = sharpness
# Array to store the points
points = []
# Iterate over the x points
for i in range(len(x)):
# Set vertex
points.append(x[i])
points.append(y[i])
# If it's not the last point
if i != (len(x) - 1):
# Insert submultiples points. The more the sharpness, the more these points will be
# closer to the vertex.
points.append((ratioMultiplier*x[i] + x[i + 1])/ratioDividend)
points.append((ratioMultiplier*y[i] + y[i + 1])/ratioDividend)
points.append((ratioMultiplier*x[i + 1] + x[i])/ratioDividend)
points.append((ratioMultiplier*y[i + 1] + y[i])/ratioDividend)
else:
# Insert submultiples points.
points.append((ratioMultiplier*x[i] + x[0])/ratioDividend)
points.append((ratioMultiplier*y[i] + y[0])/ratioDividend)
points.append((ratioMultiplier*x[0] + x[i])/ratioDividend)
points.append((ratioMultiplier*y[0] + y[i])/ratioDividend)
# Close the polygon
points.append(x[0])
points.append(y[0])
当我将这段代码改编成我的图形库时,它已经足够好了!但当我创建一个“拉伸正方形”(非正方形矩形)时,圆度也会拉伸:
那么,如何更改此代码以删除拉伸的圆度并保持其恒定半径
这里有一种方法,它使用内置的
tcl tk
原语canvas.create_line
和canvas.create_arc
来构建各种大小和比例的圆角矩形(圆弧)角半径表示为矩形
(0.0 > 0.5)
最短边的比例,可以参数化函数
make_round_corners_rect
返回一个元组,其中包含作为矩形实体片段的所有canvas item ids
。所有片段都使用其同伴的id进行标记,因此仅使用一个片段id就可以访问整个对象下一步(留给读者作为练习)是在类中封装圆形矩形
编辑:如何填充圆角矩形:
这有点复杂,从长远来看,可能需要一种方法,其中所有点都明确定义,形状形成为多边形,而不是
tkinter
原语的聚合。在此编辑中,圆角矩形由两个重叠矩形和四个圆盘填充;它允许创建填充/未填充的形状,但在创建后不更改该属性-尽管这样做不需要太多的工作。(收集画布ID,并结合outline
属性按需打开/关闭它们);然而,如前所述,将所有这些行为封装在一个模仿tk.canvas.items
行为的类中更有意义相关问题 更多 >
编程相关推荐