[Python] 纯文本查看 复制代码 # coding: utf-8
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()
|