python之canvas 画布

canvas 画布

canvas(画布)是一个矩形区域,可以放置图形、图像、组件等。

"""
测试
"""
from tkinter import *
import random
from tkinter import messagebox


class Application(Frame):
    """一个经典的GUI程序的写法"""

    def __init__(self, master=None):
        super().__init__(master)  # super代表的是父类的定义,而不是父类对象
        self.master = master
        self.pack()
        self.createWidget()

    def createWidget(self):
        """创建组件"""
        self.canvas = Canvas(self, width=400, height=350, bg='blue')
        self.canvas.pack()
        line = self.canvas.create_line(12, 12, 24, 24, 39, 52)
        # 画一条直线
        rect = self.canvas.create_rectangle(50, 50, 100, 100)
        # 画一个矩形
        oval = self.canvas.create_oval(50, 50, 100, 100)
        # 画一个圆,坐标两双,为圆的边界矩形左上角和底部右下角

        global pthoto
        pthoto = PhotoImage(file='photo/222.gif')
        self.canvas.create_image(160, 160, image=pthoto)

        Button(self, text='画十个圆', command=self.tenOval).pack(side='left')

    def tenOval(self):
        for i in range(0, 10):
            x1 = random.randrange(int(self.canvas['width']) / 2)
            x2 = random.randrange(int(self.canvas['height']) / 2)
            y1 = 9 + random.randrange(int(self.canvas['width']) / 2)
            y2 = 9 + random.randrange(int(self.canvas['height']) / 2)
            self.canvas.create_oval(x1, x2, y1, y2)


if __name__ == "__main__":
    root = Tk()
    root.geometry('400x400+200+200')
    app = Application(master=root)
    root.mainloop()

python之canvas 画布_第1张图片
python之canvas 画布_第2张图片

你可能感兴趣的:(Python—GUI编程)