帮助使用Tkinter创建Python类 [英] Help Creating Python Class with Tkinter

查看:241
本文介绍了帮助使用Tkinter创建Python类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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. 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.

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

回答您的问题: * c $ c> self.coords ?

Answering your question: what is the * in front of self.coords?

要在Tk Canvas上创建一个矩形,可以调用 create_rectangle 方法如下。

To create a rectangle on a Tk Canvas you call the create_rectangle method as follows.

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

因此每个协调器( x0 y0 等)是方法的个别参数。但是,我已经将Rectangle类的coords存储在一个单独的4元组中。我可以将这个单一的元组传递给方法调用,并在它前面放置一个 * 将它解包到四个单独的坐标值。

So each of the coords (x0, y0, etc) are indiviual paramaters to the method. However, I have stored the coords of the Rectangle class in a single 4-tuple. 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.

如果我有 self.coords =(0,0,1,1),则 create_rectangle(* self.coords)将以 create_rectangle(0,0,1,1)结束,而不是 create_rectangle((0,0,1, 1))。请注意第二个版本中的内部括号。

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)). Note the inner set of parentheses in the second version.

Python文档在 unpacking argument lists

The Python documentation discusses this in unpacking argument lists.

这篇关于帮助使用Tkinter创建Python类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆