【问题标题】:How to make a tkinter canvas rectangle with rounded corners?如何制作带圆角的 tkinter 画布矩形?
【发布时间】:2017-10-21 07:52:17
【问题描述】:

我想创建一个圆角矩形。我正在使用来自 tkinter 的画布。

【问题讨论】:

    标签: python python-3.x canvas tkinter tkinter-canvas


    【解决方案1】:

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

    如果您担心优化,或者不必担心引用单个对象的标签系统,这将具有成为一个画布对象的优势。

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

    这是一个可以做的例子:

    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_ 方法一样。

    虽然坐标看起来很复杂,但它只是有条不紊地绕到“矩形”中的每个点,给每个非角点两次。

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

    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)
    

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


    如果您想在创建矩形后更新它的位置,您可以使用这样的函数(如果在与原始canvas 对象相同的范围内):

    def update_rectangle_coords(round_rect, x1, y1, x2, y2, r=25):
        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)
        canvas.coords(round_rect, *points)
    

    所以,要更新my_rectangle 的位置(来自第一个代码示例),我们可以说:

    update_rectangle_coords(my_rectangle, 20, 20, 100, 100)
    

    【讨论】:

    • 我很惊讶这看起来这么好。当我尝试相同时,直边略微向外弯曲,就像我说的那样,就像一台旧电视。但我只使用了 12 分,而不是 20 分。不过,+1 恕我直言,使用明确的 x1,y1,x2,y2 或 x,y,w,h 参数会更好。
    • @tobias_k 我认为这种方法的诀窍是在每一侧(即远离拐角的“半径”)两次给出点,因此它们不会平滑。我也同意x1,y1,x2,y2 的建议,已编辑。
    • 我知道这是一个旧答案,但您能否以某种方式模仿 coords 函数,这样当我们尝试编辑现有圆角矩形的坐标时,我们不必处理所有多边形点。
    • @CoolCloud 查看我对答案的最新编辑 - 我们可以使用与创建矩形类似的函数来更新其位置。
    • @CoolCloud 我支持你的议案!
    【解决方案2】:

    似乎没有内置方法。最接近的应该是带有smooth=1 的折线,但它看起来仍然更像是一个旧电视屏幕,两侧也略微弯曲。

    相反,您可以定义一个辅助函数,将圆角矩形与直线和弧相结合:

    def rounded_rect(canvas, x, y, w, h, c):
        canvas.create_arc(x,   y,   x+2*c,   y+2*c,   start= 90, extent=90, style="arc")
        canvas.create_arc(x+w-2*c, y+h-2*c, x+w, y+h, start=270, extent=90, style="arc")
        canvas.create_arc(x+w-2*c, y,   x+w, y+2*c,   start=  0, extent=90, style="arc")
        canvas.create_arc(x,   y+h-2*c, x+2*c,   y+h, start=180, extent=90, style="arc")
        canvas.create_line(x+c, y,   x+w-c, y    )
        canvas.create_line(x+c, y+h, x+w-c, y+h  )
        canvas.create_line(x,   y+c, x,     y+h-c)
        canvas.create_line(x+w, y+c, x+w,   y+h-c)
    

    例子:

    import tkinter
    root = tkinter.Tk()
    canvas = tkinter.Canvas(root)
    canvas.pack()
    rounded_rect(canvas, 20, 20, 60, 40, 10)
    root.mainloop()
    

    您还可以提供另一个**options 参数来设置各个部分的线宽、颜色等,但这样做的问题是,例如线条和弧线使用不同的参数来表示线条颜色(分别为fill 和outline)。此外,如果您想要填充圆角矩形,则必须将其指定为第二种方法,使用多个矩形。

    【讨论】:

      【解决方案3】:

      我知道这篇文章已经接受了矩形的答案。但是对于那些寻找任何带有圆角的多边形(显然包括矩形)的人,我根据@SneakyTutle 的回答编写了这段代码。

      roundPolygon(x_array, y_array, sharpness, **kwargs)
      

      结果

      这背后的逻辑是启用平滑并将子点放置在顶点旁边。这样一来,只有角会变圆,而多边形的其余部分会保持平坦。

      from tkinter import *
      root = Tk()
      canvas = Canvas(root, width = 1000, height = 1000)
      canvas.pack()
      
      def roundPolygon(x, y, sharpness, **kwargs):
      
          # 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])
      
          return canvas.create_polygon(points, **kwargs, smooth=TRUE)
      
      my_rectangle = roundPolygon([50, 350, 350, 50], [50, 50, 350, 350], 10 , width=5, outline="#82B366", fill="#D5E8D4")
      my_triangle = roundPolygon([50, 650, 50], [400, 700, 1000], 8 , width=5, outline="#82B366", fill="#D5E8D4")
      
      root.mainloop()
      

      我想不出一个使锐度正常化的好方法。无论如何,2 到 10 之间的东西对任何情况都有好处。随意更改代码。

      仅用于可视化,对于具有 sharpness=8 的三角形,for 循环的结果代码如下。您可能会注意到,如果锐度为 2,则子点将放置在顶点的中间。

      points = [
            # Begin vertex
            x[0], y[0],
            # Between vertices
            (7*x[0] + x[1])/8, (7*y[0] + y[1])/8,
            (7*x[1] + x[0])/8, (7*y[1] + y[0])/8,
            # Vertex
            x[1], y[1],
            # Between vertices
            (7*x[1] + x[2])/8, (7*y[1] + y[2])/8,
            (7*x[2] + x[1])/8, (7*y[2] + y[1])/8,
            # Vertex
            x[2], y[2],
            # Between vertices
            (7*x[2] + x[0])/8, (7*y[2] + y[0])/8,
            (7*x[0] + x[2])/8, (7*y[0] + y[2])/8,
            # End/Begin vertex
            x[0], y[0]
          ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 2020-06-30
        • 1970-01-01
        相关资源
        最近更新 更多