繁体   English   中英

使用Tkinter帮助创建Python类

[英]Help Creating Python Class with Tkinter

如何创建一个名为“矩形”的类,我可以将其传递给它的坐标和颜色并将其填充到其中?

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

这是一种方法。 首先,要在Tk画布上绘制矩形,您需要调用Canvas的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前面的*self.coords

要在Tk画布上创建矩形,请按如下所示调用create_rectangle方法。

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

因此,每个坐标( x0y0等)都是该方法的单独参数。 但是,我已经将Rectangle类的坐标存储在单个4元组中。 我可以将此单个元组传递给方法调用,并在其前面加上*将其解压缩为四个单独的坐标值。

如果我有self.coords = (0, 0, 1, 1)然后create_rectangle(*self.coords)最终将成为create_rectangle(0, 0, 1, 1)而不是create_rectangle((0, 0, 1, 1)) 注意第二个版本中的内部括号。

Python文档在解压缩参数列表中对此进行了讨论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM