如何使用类在tkinter画布上配置多边形?

时间:2015-11-22 14:02:20

标签: python tkinter tkinter-canvas

这是我当前的工作代码,但我想在一个函数中添加一个将在' mainloop'中改变形状颜色的函数:

from Tkinter import*

root = Tk()

class GUI(Canvas):
    '''inherits Canvas class (all Canvas methodes, attributes will be accessible)
   You can add your customized methods here.
   '''
    def __init__(self,master,*args,**kwargs):
        Canvas.__init__(self, master=master, *args, **kwargs)

polygon = GUI(root)
polygon.create_polygon([150,75,225,0,300,75,225,150],     outline='gray', 
        fill='gray', width=2)

polygon.pack()
root.mainloop()

我在想这样的事情(在课堂内):

def configure(self,colour):
    Canvas.itemconfig(self,fill=colour)

然后我称之为:

polygon.configure('red')

但我一直收到这个错误,我不知道如何修复它:

Exception in Tkinter callback
File "C:/Users/User/Documents/Algies homework/Hexaheaflexagon sim.py", line 117, in configure
Canvas.itemconfig(self,fill=colour)
TypeError: itemconfigure() missing 1 required positional argument: 'tagOrId'

1 个答案:

答案 0 :(得分:1)

我尝试这样做

from Tkinter import*

# --- class ---

class GUI(Canvas):
    '''inherits Canvas class (all Canvas methodes, attributes will be accessible)
   You can add your customized methods here.
   '''
    def __init__(self,master,*args,**kwargs):
        Canvas.__init__(self, master=master, *args, **kwargs)
        # default - poly not exists
        self.poly = None

    def create_poly(self, points, outline='gray', fill='gray', width=2):
        # remember poly
        self.poly = self.create_polygon(points, outline=outline, fill=fill, width=width)

    def set_poly_fill(self, color):
        # if poly exists then you can change fill
        if self.poly:
            self.itemconfig(self.poly, fill=color)

# --- main ---

root = Tk()

polygon = GUI(root)
polygon.create_poly([150,75,225,0,300,75,225,150])
polygon.set_poly_fill('red')
polygon.pack()

root.mainloop()