[英]Help Creating Python Class with Tkinter
How do I create a class called rectangle that I can pass it the coordinates and a color and have it fill those one? 如何创建一个名为“矩形”的类,我可以将其传递给它的坐标和颜色并将其填充到其中?
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()
Here is one way of doing it. 这是一种方法。 First, to draw the rectangle on the Tk Canvas you need to call the
create_rectangle
method of the Canvas. 首先,要在Tk画布上绘制矩形,您需要调用Canvas的
create_rectangle
方法。 I also use the __init__
method to store the attributes of the rectangle so that you only need to pass the Canvas object as a parameter to the rectangle's draw()
method. 我还使用
__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()
EDIT 编辑
Answering your question: what is the *
in front of self.coords
? 回答您的问题:
self.coords
前面的*
是self.coords
?
To create a rectangle on a Tk Canvas you call the create_rectangle
method as follows. 要在Tk画布上创建矩形,请按如下所示调用
create_rectangle
方法。
Canvas.create_rectangle(x0, y0, x1, y1, option, ...)
So each of the coords ( x0
, y0
, etc) are indiviual paramaters to the method. 因此,每个坐标(
x0
, y0
等)都是该方法的单独参数。 However, I have stored the coords of the Rectangle class in a single 4-tuple. 但是,我已经将Rectangle类的坐标存储在单个4元组中。 I can pass this single tuple into the method call and putting a
*
in front of it will unpack it into four separate coordinate values. 我可以将此单个元组传递给方法调用,并在其前面加上
*
将其解压缩为四个单独的坐标值。
If I have self.coords = (0, 0, 1, 1)
, then create_rectangle(*self.coords)
will end up as create_rectangle(0, 0, 1, 1)
, not create_rectangle((0, 0, 1, 1))
. 如果我有
self.coords = (0, 0, 1, 1)
然后create_rectangle(*self.coords)
最终将成为create_rectangle(0, 0, 1, 1)
而不是create_rectangle((0, 0, 1, 1))
。 Note the inner set of parentheses in the second version. 注意第二个版本中的内部括号。
The Python documentation discusses this in unpacking argument lists . Python文档在解压缩参数列表中对此进行了讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.