代码之家  ›  专栏  ›  技术社区  ›  Noah Clark

帮助使用Tkinter创建Python类

  •  0
  • Noah Clark  · 技术社区  · 15 年前

    如何创建一个名为rectangle的类来传递坐标和颜色,并让它填充这些坐标和颜色?

    from Tkinter import *
    master = Tk()
    
    w = Canvas(master, width=300, height=300)
    w.pack()
    
    class rectangle():
    
        def make(self, ulx, uly, lrx, lry, color):
            self.create_rectangle(ulx, uly, lrx, lry, fill=color)
    
    
    rect1 = rectangle()
    rect1.make(0,0,100,100,'blue')
    
    mainloop()
    
    1 回复  |  直到 15 年前
        1
  •  3
  •   Gary Kerr    15 年前

    这里有一种方法。首先,要在Tk画布上绘制矩形,需要调用 create_rectangle 画布的方法。我也使用 __init__ 方法来存储矩形的属性,这样您只需要将Canvas对象作为参数传递给矩形的 draw() 方法。

    from Tkinter import *
    
    class Rectangle():
        def __init__(self, coords, color):
            self.coords = coords
            self.color = color
    
        def draw(self, canvas):
            """Draw the rectangle on a Tk Canvas."""
            canvas.create_rectangle(*self.coords, fill=self.color)
    
    master = Tk()
    w = Canvas(master, width=300, height=300)
    w.pack()
    
    rect1 = Rectangle((0, 0, 100, 100), 'blue')
    rect1.draw(w)
    
    mainloop()
    

    回答你的问题:什么是 * 在前面 self.coords ?

    Canvas.create_rectangle(x0, y0, x1, y1, option, ...)
    

    所以每个坐标( x0 y0 等)是该方法的单独参数。但是,我将矩形类的坐标存储在一个4元组中。我可以将这个元组传递到方法调用中,并将 在它前面,将把它分解成四个独立的坐标值。

    如果我有 self.coords = (0, 0, 1, 1) create_rectangle(*self.coords) 最终会变成 create_rectangle(0, 0, 1, 1) create_rectangle((0, 0, 1, 1)) . 请注意第二个版本中的内圆括号集。

    Python文档详细讨论了这一点 unpacking argument lists .

    推荐文章