且构网

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

如何制作带有圆角的tkinter画布矩形?

更新时间:2023-01-03 22:45:29

为tobias方法提供另一种方法实际上是使用一个多边形来完成。

Offering an alternate approach to tobias's method would be to indeed do it with one polygon.

如果您担心优化,或者不必担心标记系统引用单个对象,这将是一个画布对象。

This would have the advantage of being one canvas object if you are worried about optimization, or not having to worry about a tag system for referring to a single object.

代码有点长,但是非常基本,因为它只是利用了这样的想法:在平滑多边形时,您可以两次给出相同的坐标来停止平滑

The code is a bit longer, but very basic, as it is just utilizing the idea that when smoothing a polygon, you can give the same coordinate twice to 'stop' the smooth from occuring.

这是可以执行的操作示例:

This is an example of what can be done:

from tkinter import *
root = Tk()
canvas = Canvas(root)
canvas.pack()

def round_rectangle(x1, y1, x2, y2, radius=25, **kwargs):

    points = [x1+radius, y1,
              x1+radius, y1,
              x2-radius, y1,
              x2-radius, y1,
              x2, y1,
              x2, y1+radius,
              x2, y1+radius,
              x2, y2-radius,
              x2, y2-radius,
              x2, y2,
              x2-radius, y2,
              x2-radius, y2,
              x1+radius, y2,
              x1+radius, y2,
              x1, y2,
              x1, y2-radius,
              x1, y2-radius,
              x1, y1+radius,
              x1, y1+radius,
              x1, y1]

    return canvas.create_polygon(points, **kwargs, smooth=True)

my_rectangle = round_rectangle(50, 50, 150, 100, radius=20, fill="blue")

root.mainloop()

使用此功能,您只需提供要用于矩形的法线坐标,然后指定圆角处的半径。 ** kwargs 的使用表示您可以像 fill = blue 这样传递关键字参数通常可以使用 create _ 方法。

Using this function, you can just provide the normal coordinates that you would to a rectangle, and then specify the 'radius' which is rounded in the corners. The use of **kwargs denotes that you can pass keyword arguments such as fill="blue", just as you usually could with a create_ method.

尽管坐标看起来很复杂,但它只是有条不紊地围绕每个点

Although the coords look complex, it is just going around methodically to each point in the 'rectangle', giving each non-corner point twice.

如果您不介意较长的代码行,则可以将所有坐标放在一个矩形上。行,使函数只有2行(!)。看起来像这样:

If you didn't mind a rather long line of code, you could put all the coordinates on one line, making the function just 2 lines(!). This looks like:

def round_rectangle(x1, y1, x2, y2, r=25, **kwargs):    
    points = (x1+r, y1, x1+r, y1, x2-r, y1, x2-r, y1, x2, y1, x2, y1+r, x2, y1+r, x2, y2-r, x2, y2-r, x2, y2, x2-r, y2, x2-r, y2, x1+r, y2, x1+r, y2, x1, y2, x1, y2-r, x1, y2-r, x1, y1+r, x1, y1+r, x1, y1)
    return canvas.create_polygon(points, **kwargs, smooth=True)

这将产生以下内容(请注意,这是一个画布对象):

This produces the following (Note in mind this is ONE canvas object):