如何在tkinter中平滑椭圆形周围的边缘?

问题描述

我是 tkinter 的新手,我最近了解了 canvas 小部件。在掌握了基础知识之后,我认为我可以使用画布制作一个自定义进度栏,并且可以正常工作!确实很棒,但是,删除形状的轮廓后,我发现形状的边缘相当粗糙,尤其是椭圆形。我做了一些搜索,发现您只能将 smooth 关键字参数与多边形一起使用。所以我的问题是,有没有一种方法可以使tkinter中的形状尤其是椭圆形的边缘变平滑,就像 anti-aliasing ?我的代码

from tkinter import *

root = Tk()
root.geometry("500x500")
percent = 0
progress_done,new_oval = None,None
canvas = Canvas(root,width=400,height=400,bg="white")
canvas.pack(pady=10)
prg_bar = canvas.create_rectangle(50,140,350,160,fill="grey",outline="")
oval_one = canvas.create_oval(40,60,outline="",)
oval_two = canvas.create_oval(340,360,outline="")


def add_up():
    global percent,progress_done,new_oval
    if percent < 100:
        percent += 20
        if progress_done is None and new_oval is None:
            canvas.create_oval(40,fill="light blue",outline='')
            canvas.delete(oval_one)
            progress_done = canvas.create_rectangle(50,(percent * 3) + 50,outline="")
            new_oval = canvas.create_oval((percent * 3) + 40,(percent * 3) + 60,outline="")
        else:
            canvas.delete(progress_done)
            canvas.delete(new_oval)
            progress_done = canvas.create_rectangle(50,outline="")
            if percent == 100:
                canvas.delete(oval_two)


btn = Button(root,text="Add to prg",command=add_up)
btn.pack()
root.mainloop()

解决方法

使用create_polygon绘制椭圆形。下面是绘制椭圆形和圆形矩形的示例。两个示例都设置了splinesteps选项,以增强所生成曲线的平滑度。 splinesteps选项默认为12。

import tkinter as tk
root = tk.Tk()

c = tk.Canvas(root)
c.pack(fill='both',expand=True,anchor='nw')

def poly_oval(x,y,width,height,resolution=32):
    points = [x,x+width,y+height,x,y]
              
    return c.create_polygon(points,fill='#f00',smooth=True,splinesteps=resolution)   
    
def poly_roundrect(x,radius,resolution=32):
    #this is not a true round rect
    #it's a round rect with the potential to have invisible garbage that cheats
    #it cheats convincingly if you don't use an outline when it is cheating
    radius = min(min(width,height),radius*2)
    points = [x,x+radius,x+(width-radius),y+radius,y+(height-radius),y]
              
    rect = c.create_polygon(points,fill='#1f1',splinesteps=resolution) 
    
    #display vertices
    #for i in range(0,len(points),2):
    #    poly_oval(points[i]-2,points[i+1]-2,4,4)
              
    return rect
    
rect = poly_roundrect(10,10,300,50,64)

root.mainloop()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...