10.4Python图形用户界面库tkinter(4):画布与绘图

class CanvasDemo:

    def __init__(self):

        # 窗口和标题
        window = Tk()
        window.title("画布")

        # 打包一个画布到窗口
        self.canvas = Canvas(window, width=400, height=300, bg="#FFFFFF")
        self.canvas.pack()

        # 打包一个面板到窗口
        frame1 = Frame()
        frame1.pack()

        # 在面板1上创建一堆按钮
        btnRect = Button(frame1, text="矩形", command=self.drawRect)
        btnOval = Button(frame1, text="椭圆", command=self.drawOval)
        btnArc = Button(frame1, text="弧形", command=self.drawArc)
        btnPoly = Button(frame1, text="多边形", command=self.drawPolygon)
        btnLine = Button(frame1, text="线条", command=self.drawLine)
        btnStr = Button(frame1, text="字符", command=self.drawString)
        btnClear = Button(frame1, text="清空", command=self.clearAll)

        # 在面板1上表格排列这些按钮
        btnRect.grid(row=1, column=1)
        btnOval.grid(row=1, column=2)
        btnArc.grid(row=1, column=3)
        btnPoly.grid(row=1, column=4)
        btnLine.grid(row=1, column=5)
        btnStr.grid(row=1, column=6)
        btnClear.grid(row=1, column=7)

        # 开启消息循环
        window.mainloop()

    # 绘制矩形
    def drawRect(self):
        # 左上角坐标(10,10)、右下角坐标(190,90)、别名rect、填充为黄色
        self.canvas.create_rectangle(10, 10, 190, 90, tag="rect",width=9,fill="yellow")

    # 绘制椭圆
    def drawOval(self):
        # 左上角坐标(10,10)、右下角坐标(190,90)、别名oval、填充为red
        self.canvas.create_oval(10, 10, 190, 90, fill="red", tag="oval")

    # 画弧形
    def drawArc(self):
        # 左上角坐标(10,10)、右下角坐标(190,90)、别名arc、填充为red、起始角度0-359
        self.canvas.create_arc(10, 10, 190, 90, start=0, extent=359, fill="red", tag="arc")

    # 多边形
    def drawPolygon(self):
        # 左上角坐标(10,10)、右下角坐标(190,90)、别名polygon、填充为red
        self.canvas.create_polygon(10, 10, 190, 90, 30, 50, fill="red", tag="polygon")

    # 画线
    def drawLine(self):
        self.canvas.create_line(10, 10, 190, 90, 30, 50, tag="line")
        # 依次经过(10,10)(190,90)(30,50)、线粗9,别名line、填充为blue,激活态为red,箭头指向始端(还可以是last)
        self.canvas.create_line(10, 90, 190, 10, 30, 50, width=9, arrow="first", fill="blue", activefill="red",tag="line")

    # 画字符
    def drawString(self):
        # 字符中心在(100,100),内容为Hello,字体华文20号,别名string
        self.canvas.create_text(100, 100, text="Hello Tkinter!", font=("华文行楷",20),tag="string")

    # 清除图形
    def clearAll(self):
        # 清除指定别名的图形
        self.canvas.delete("rect","oval","arc","line","string","polygon")

执行效果
10.4Python图形用户界面库tkinter(4):画布与绘图_第1张图片
10.4Python图形用户界面库tkinter(4):画布与绘图_第2张图片

你可能感兴趣的:(Python,语言程序设计)