如何使用类在tkinter画布上绘制多边形?

时间:2015-11-17 12:45:59

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

from tkinter import*

root = Tk()
shape = Canvas(root)

class GUI():
    def __init__(self):
        pass

    def create_polygon(self, points, colour, posit):
        try:
            shape.delete(self.poly)
        except:
            pass
        self.poly = shape.create_polygon(points, colour, posit)
        self.poly.shape.grid(column=posit[0],row=posit[1])

polygon = GUI()
polygon.create_polygon([150,75,225,0,300,75,225,150],'yellow',[1,2])

我是使用tkinter和类的新手,但我想创建一个非常简单的类来创建一个正多边形。这个程序中的代码应该删除以前制作的任何多边形,然后在调用程序时继续创建一个新的多边形但是我一直收到一个我不理解的错误。另外你会怎样画六角形呢?

Traceback (most recent call last):
  File "//xsvr-02/Students/10SAMP_Al/HW/polygon creator.py", line 19, in <module>
polygon.create_polygon([150,75,225,0,300,75,225,150],'yellow',[1,2])
 File "//xsvr-02/Students/10SAMP_Al/HW/polygon creator.py", line 15, in create_polygon
self.poly = shape.create_polygon(points, colour, posit)
 File "C:\Python34\lib\tkinter\__init__.py", line 2305, in create_polygon
return self._create('polygon', args, kw)
File "C:\Python34\lib\tkinter\__init__.py", line 2287, in _create
*(args + self._options(cnf, kw))))
_tkinter.TclError: wrong # coordinates: expected an even number, got 11

1 个答案:

答案 0 :(得分:2)

这只是错误的调用参数。

如果您想更改代码,此解决方案可以为您提供帮助。

类GUI只是从Canvas继承而来,并没有实现任何东西。

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()

如需更多帮助,请添加评论。