对于 python 中的自我开发项目,我正在尝试创建一个算法动画程序,但我目前被困在我项目的动画部分。所以我已经让条形图显示在 tkinter 画布上,但我不知道如何让条形图动画化。PS我是python的新手,所以对代码的解释会很有帮助,或者只是对前进的最佳方式的任何解释,谢谢
from algorithms import *
from tkinter import *
import random
import time
a_list = [] # values of the list I want to sort, starts empty
bar_coords = [] # list of lists of coordinates for each of the bars represented in the canvas
def initialize_list_elements(num_of_elements, up_to):
list_of_numbers = []
canvas.delete('all')
for _ in range(num_of_elements):
list_of_numbers.append(random.randint(1, up_to))
return list_of_numbers
def clear_list():
a_list.clear()
canvas.delete('all')
return a_list
def draw():
x = 0
a_list = initialize_list_elements(30, 600)
for value in a_list: # so for each value in our list of values
x = x + 30 # each
y = 700 - int(value) # assign a point y
bars = canvas.create_line((x, 700, x, y), width = 10, fill='black') # then we draw a line using the points (x, 200) and (x, y)
canvas.create_text(x, y-10, text=str(value))
bar_coords = canvas.coords(bars)
algorithm_list = ['Binary Search', 'Jump Search', 'Linear Search', 'Bubble Sort', 'Heap Sort', 'Insertion Sort', 'Merge Sort', 'Quick Sort', 'Selection Sort']
window = Tk()
window.title('Algorithm Testbed')
title_frame = Frame(window) # a frame used to display the title of the program
button_frame = Frame(window) # a frame to hold the buttons
canvas_frame = Frame(window) # a frame for the canvas
var = StringVar(button_frame)
var.set(algorithm_list[0])
canvas = Canvas(canvas_frame, width=910, height=700, background='white')
title_label = Label(title_frame, text='Searching & Sorting Algorithm Testbed', font='Helvetica 20 bold')
init_button = Button(button_frame, text=' Initialise ', width=15, pady=10, command=draw)
start_button = Button(button_frame, text=' Start ', width=15, pady=10)
pause_button = Button(button_frame, text=' Pause ', width=15, pady=10)
step_button = Button(button_frame, text=' Step ', width=15, pady=10)
clear_button = Button(button_frame, text=' Clear ', width=15, pady=10, command=clear_list)
drop_down_menu = OptionMenu(button_frame, var, *algorithm_list)
# putting the label onto the title_frame
title_label.grid(rowspan=2, column=0)
# putting buttons onto the button_frame
init_button.grid(rowspan=1, column=0, pady=10, padx=5)
start_button.grid(rowspan=1, column=0, pady=10, padx=5)
pause_button.grid(row=2, column=0, pady=10, padx=5)
step_button.grid(row=3, column=0, pady=10, padx=5)
clear_button.grid(row=4, column=0, pady=10, padx=5)
drop_down_menu.grid(row=5, column=0, pady=10, padx=5)
# putting canvas onto canvas_frame
canvas.grid(row=0, column=0)
# putting frames on the window
title_frame.grid(row=0, columnspan=2)
button_frame.grid(row=1, column=0)
canvas_frame.grid(row=1, column=1)
window.mainloop()
我的算法代码我已经遗漏了,因为在不同的文件中,该文件大约有 200 行代码,不想用太多代码堵塞。但是我在 tkinter 画布上绘制横条的地方就在那里,再次感谢您的任何建议。