【问题标题】:How to configure a polygon on a tkinter canvas using a class?如何使用类在 tkinter 画布上配置多边形?
【发布时间】:2015-11-22 14:02:19
【问题描述】:

这是我当前的工作代码,但我想添加一个在“主循环”期间改变形状颜色的函数:

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'

【问题讨论】:

  • 显然这是作业。我认为目的是在类中创建一个多边形,以及在类中创建一个更改颜色的方法/函数(并且该类必须知道对多边形对象的引用才能更改颜色)。您还必须创建该类的一个实例。有关入门信息,请参阅此链接,并且 calculateArea() 函数代表您将如何更改颜色 freenetpages.co.uk/hp/alan.gauld/tutclass.htm
  • 这是家庭作业,但你错了,我正在制作一个六边形模拟器,我已经有了实际节点和转换以及其他小部件和 GUI 设置的工作类和代码,为链接欢呼:) 看起来很有希望

标签: python tkinter tkinter-canvas


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多