好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python tkinter库绘图实例分享

一、小房子绘制

实例代码:

# coding=utf-8
import tkinter as tk ? ? ?# 导入tkinter模块
?
root = tk.Tk() ? ? ? ? ? ?# 创建一个顶级窗口
root.title('小房子1') ? ? # 设置标题
canvas = tk.Canvas(root, bg='white', width=700, height=700) ? # 在root窗口上创建画布canvas,白色背景,宽和高均为700像素
canvas.pack(anchor='center') ? # canvas在root上居中显示
?
points = [(50, 250), (350, 50), (650, 250)] ? # 三角形顶点坐标位置
canvas.create_polygon(points, fill='gray', outline='black', width=10) ? # 白色填充,红色线条,线宽为10
canvas.create_rectangle((200, 250, 500, 550),
? ? ? ? ? ? ? ? ? ? ? ? fill='white', outline='black', width=10) ? ? # 绘制矩形,白色填充,绿色线条,线宽为10
canvas.create_oval((250, 300, 450, 500),
? ? ? ? ? ? ? ? ? ?fill='purple', outline='black', width=10) ? ?# 绘制圆形,黄色填充,黄色线条,线宽为10
?
root.mainloop() ? # 进入消息循环

运行结果:

二、彩色气泡动画绘制

实例代码:

#coding=utf-8
import tkinter as tk
import random as rd
import time
# 全局变量,全部为list对象
# 分别为:x方向速度,y方向速度,半径,位置,图形标记
speedXList, speedYList, rList, posList, idList = [], [], [], [], []
# 可选的颜色
colorList = ['pink', 'gold', 'lightblue', 'lightgreen', 'silver']
# 画布的宽度、高度,以及图形个数
width, height, num = 400, 400, 5
root = tk.Tk()
# 创建和布局画布
canvas = tk.Canvas(root, width=width, height=height, background='white')
canvas.pack()
?
for i in range(num):
?? ?# 随机产生图形初始位置
? ? x = rd.randint(100, width - 100)
? ? y = rd.randint(100, height - 100)
? ? # 添加到图形位置列表
? ? posList.append((x, y))
? ? # 随机产生半径,并添加到半径列表
? ? r = rd.randint(20, 50)
? ? rList.append(r)
? ? # 随机选取一种颜色
? ? color = rd.sample(colorList, 1)
? ? # 创建一个椭圆/圆,用选定的颜色填充
? ? id = canvas.create_oval(x - r, y - r, x + r, y + r,
? ? ? ? ? ? ? ? ? ? ? ? ? ? fill=color, outline=color)
? ? # 保存图形标识
? ? idList.append(id)
# 设置随机的移动速度,并保存
? ? speedXList.append(rd.randint(-10, 10))
? ? speedYList.append(rd.randint(-10, 10))
?
while True:
? ? for i in range(num):
? ? ? ? # 图形当前所在位置
? ? ? ? item = posList[i]
? ? ? ? r = rList[i]
? ? ? ? ?# 如果x位置超过边界,则改编x速度方向
? ? ? ? if item[0] - r < 0 or item[0] + r > width:
? ? ? ? ? ? speedXList[i] = -speedXList[i]
? ? ? ? # 如果y位置超过边界,则改编y速度方向
? ? ? ? if item[1] - r < 0 or item[1] + r > height:
? ? ? ? ? ? speedYList[i] = -speedYList[i]
? ? ? ? # 按照当前的速度计算下新的位置
? ? ? ? posList[i] = (item[0] + speedXList[i], item[1] + speedYList[i])
? ? ? ? x, y = posList[i][0], posList[i][1]
? ? ? ? # 移动到新的位置
? ? ? ? canvas.coords(idList[i], (x - r, y - r, x + r, y + r))
? ? ? ? # 刷新画面
? ? ? ? canvas.update()
? ? # 等待0.1秒,即每秒钟更新10帧,形成动画
? ? time.sleep(0.1)

运行结果:

三、画布创建

实例代码:

import tkinter as tk ? ? ? ? ? # 导入tkinter库,并重命名为tk
mywindow = tk.Tk() ? ? ? ? ? ? # 创建一个窗体
mywindow.title("我是一个画布") ? ? ?# 设置窗体的标题
mycanvas = tk.Canvas(mywindow, width=400, height=300, bg="purple") ?# 创建画布并布局
?
mycanvas.pack()
mywindow.mainloop() ? ? ?# 显示画布

运行结果:

到此这篇关于Python tkinter库绘图实例分享的文章就介绍到这了,更多相关tkinter库绘图内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于Python tkinter库绘图实例分享的详细内容...

  阅读:48次