案例介绍
我们将使用 python 的 tkinter 实现插入排序的动画演示,实现两个功能:1. 重置数据。2. 用户控制每一步的进行。
将要学习:1. 如何删除某个对象。2. 针对数字大小不同的情况,图表如何呈现?
准备工作
- Python 3.x
- 插入排序:插入排序是一种最简单的排序方法,它的基本思想是将一个记录插入到已经排好序的有序表中,从而一个新的、记录数增1的有序表。
界面模块
界面分为两个部分,首先是序列的显示部分,然后是两个交互按钮——单步执行、重置数据。
【key points】
- 如何删除某个对象?
我们要在画布上绘制每个小矩形,画布初始化语句:
canvas = tk.Canvas(root, bg='white', height=400, width=1000)
canvas.place(x=0, y=0)
每个矩形都有一个 tags 属性来标示每个矩形:
canvas.create_rectangle(x0, y0 - sortL[index][i] * 10, x0 + width, y0, width=3, fill='red', tags=str(i))
删除的时候,只需要删除对应 tags 的矩形即可:
canvas.delete(str(i))
- 图表上如何体现每个数字?
如何使用不同的矩形高度表示不同的数字,首先,我们需要知道在 tkinter 中坐标系是如何构建的,在 tkinter 中,坐标原点处于左上角,向右为 x 轴正方向,向下为 y 轴正方向。 然后,我们需要知道如何在画布上绘制一个矩形,绘制矩形,需要传入两个坐标——矩形左上角点的 X,Y 坐标,还有矩形右下角点的 X,Y 坐标。
canvas.create_rectangle(x0, y0 - sortL[index][i] * 10, x0 + width, y0, width=3, tags=str(i))
其中,这两个坐标的横坐标很好理解,就是 x0 和 x0+矩形宽度。纵坐标和数字大小有关,我们设定最大数字为30,每大1,高度就增加 10 px,所以只需要使用 300-数字大小*10 即可得出 y 坐标,为了上方能够有空白,我们使用 350 作为被减数。
代码汇总
# coding: utf-8
# !/usr/bin/python
"""
@File : 动画演示插入排序.py
@Author : jiaming
@Modify Time: 2020/5/8 20:20
@Contact :
@WeChat 答疑 :
@Desciption : None
"""
import tkinter as tk
import random
import copy
import tkinter.messagebox
width = 30 # 矩形条宽度
x0 = 80 # 矩形条x轴初始值
y0 = 350 # 矩形条最高度
index = 0 # 待排序数字的下标标记
sortL = [] # 存储插入排序的每一步结果
root = tk.Tk()
root.title("动画演示插入排序")
root.geometry('640x500+250+250')
root.resizable(False, False)
def insertSort():
"""
生成随机数组, 并且保存插入排序的每步结果, 保存到sortL
:param num:
:return:
"""
global sortL
# 随机生成数据列表
num = [i for i in range(1, 31, 1)]
random.shuffle(num)
num = num[:15] # 取随机数组的前15个组成列表
sortL.append(copy.deepcopy(num)) # 存储每次排序结果
# 插入排序算法
for i in range(1, len(num)):
key = num[i]
j = i - 1
while j >= 0 and key < num[j]:
num[j + 1] = num[j]
j -= 1
num[j + 1] = key
sortL.append(copy.deepcopy(num)) # 存储每次排序结果
sortL.append(copy.deepcopy(num))
def draw():
"""
绘制结果
:return:
"""
global width, x0, y0, index, sortL
x0 = 80 # x 坐标初始化
print(sortL[index])
def step():
# 删除每一个矩形以及字符
for i in range(15):
canvas.delete(str(i))
canvas.delete("string" + str(i))
draw() # 重新绘制
stepBtn = tk.Button(root, text="单步排序", width=8, height=1, command=step)
stepBtn.place(x=200, y=420)
def reset():
global index
index = 0
sortL.clear() # 清空结果列表
insertSort() # 执行插入排序算法
draw() # 绘制结果列表中的每一项
resetBtn = tk.Button(root, text="重置数据", width=8, height=1, command=reset)
resetBtn.place(x=350, y=420)
canvas = tk.Canvas(root, bg='white', height=400, width=1000)
canvas.place(x=0, y=0)
for i in range(15):
# 绘制矩形条
if index + 1 == i: # 用红色标记待排序的数字
canvas.create_rectangle(x0, y0 - sortL[index][i] * 10,
x0 + width, y0, width=3, fill='red',
tags=str(i))
else:
canvas.create_rectangle(x0, y0 - sortL[index][i] * 10, x0 + width,
y0, width=3, tags=str(i))
# 绘制文本
canvas.create_text(x0 + width // 2, y0 - sortL[index][i] * 10 -
width // 2, text=str(sortL[index][i]),
font="time 10 bold underline",
tags="string" + str(i))
x0 = x0 + width
if index == 14:
tk.messagebox.showinfo('信息', '排序完成')
index += 1
if __name__ == "__main__":
insertSort()
draw()
root.mainloop()
运行截图
后记
以上就是如何使用 tkinter 来演示插入排序的全部内容了,希望你们喜欢。
欢迎关注我的我的知乎专栏,里面有更多关于 python 的精彩知识分享哦~