В настоящее время я работаю над визуализацией различных алгоритмов сортировки и сейчас пытаюсь встроить анимацию в tkinker gui для простоты использования. Анимации сделаны с помощью matplotlib и используют гистограммы. В настоящее время я изо всех сил пытаюсь заставить графики быть анимированными. Я работал без gui, но в настоящее время я получаю график c в gui. Пожалуйста, мог бы я дать несколько советов о том, как исправить это. Полный код на данный момент можно найти на https://github.com/MGedney1/Sorting_Algorithm_Visualisation
Код области интересов:
import random
import time
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
from tkinter import Frame,Label,Entry,Button
def bubble_sort(lst): #Bubble Sort
index = len(lst) - 1
while index >= 0:
test_index = index
while test_index >= 0:
if lst[index] < lst[test_index]:
temp = lst[index]
lst[index] = lst[test_index]
lst[test_index] = temp
test_index -= 1
yield lst
index -= 1
class Window(Frame):
def __init__(self, master = None):
Frame.__init__(self,master)
self.master = master
self.set_up_window()
def update_fig(self): #Update fig function
for self.rect, val in zip(self.rects,self.unordered): #Setting height of the rectangles
self.rect.set_height(val)
self.iteration[0] += 1
text.set_text("# of operations: {}".format(iteration[0]))
def set_up_window(self):
n,self.unordered = create_array()
title = 'Test'
generator = bubble_sort(self.unordered)
self.fig,self.ax = plt.subplots() #Creating axis and figure
self.bar_rects = self.ax.bar(range(len(self.unordered)), self.unordered, align="edge") #Creating the rectangular bars
self.ax.set_xlim(0, n) #Axis limits
self.ax.set_ylim(0, int(1.07 * n))
self.text = self.ax.text(0.02, 0.95, "", transform=self.ax.transAxes) #Number of operations counter
self.iteration = [0]
self.anim = animation.FuncAnimation(self.fig, func=self.update_fig, frames=generator, interval=1,repeat=False) #Creating the animatio
self.canvas = FigureCanvasTkAgg(self.fig, master=root)
self.canvas.get_tk_widget().grid(column=0,row=1)
if __name__ == '__main__':
root = tk.Tk()
root.geometry("700x400")
app = Window(root)
tk.mainloop()