1
+ from tkinter import *
2
+ from tkinter import ttk
3
+ from ttkbootstrap import *
4
+ from numpy import linspace , random , uint16
5
+ import time
6
+
7
+ class App :
8
+ def __init__ (self ,root ,title ) -> None :
9
+ self .root = root
10
+ self .root .title (title )
11
+ self .root .geometry ('805x440' )
12
+ ttk .Button (self .root ,text = 'start sorting' ,command = self ._start ).grid (row = 0 ,column = 14 )
13
+ ttk .Button (self .root ,text = 'shuffle' ,command = self ._shuffle ).grid (row = 0 ,column = 13 )
14
+ self .canvas = Canvas (self .root ,width = 800 ,height = 405 ,highlightbackground = 'dodgerblue' ,
15
+ bg = 'black' ,highlightthickness = 2 )
16
+ self .canvas .grid (row = 1 ,columnspan = 15 )
17
+ self .N = 50
18
+ self .data = linspace (5 ,400 ,self .N )
19
+ self ._colors = ['dodgerblue' for _ in range (self .N )]
20
+ self ._speed = 5 / 1000
21
+ # colors
22
+ self ._shuffle ()
23
+
24
+ def __reset_colors (self ,color = 'dodgerblue' ):
25
+ self ._colors = [color for _ in range (self .N )]
26
+
27
+ def _shuffle (self ):
28
+ self .__reset_colors ()
29
+ random .shuffle (self .data )
30
+ self ._display (self ._colors )
31
+
32
+ def _display (self ,array_color :list ):
33
+ g = self .N * 0.01 # gap
34
+ width = lambda x :(800 - 99 * x )/ self .N
35
+ self .canvas .delete ('all' )
36
+
37
+ for i in range (self .N ):
38
+ # self.canvas.create_rectangle(x0,y0,
39
+ # x1,y1,
40
+ # fill='blue')
41
+ x0 = i * width (g )+ i * g
42
+ y0 = 0
43
+ x1 = (i + 1 )* width (g )+ i * g
44
+ y1 = self .data [i ]
45
+ self .canvas .create_rectangle (x0 ,y0 ,x1 ,y1 ,fill = array_color [i ])
46
+
47
+ self .root .update_idletasks ()
48
+
49
+ def _start (self ):
50
+ for steps in range (self .N - 1 ):
51
+ a = self .N - 1 - steps
52
+ for i in range (a ):
53
+ self ._colors [i ] = self ._colors [i + 1 ] = 'yellow'
54
+ self ._display (self ._colors )
55
+ time .sleep (self ._speed )
56
+ if self .data [i ]> self .data [i + 1 ]:
57
+ self ._colors [:a + 1 ] = ['dodgerblue' ]* (a + 1 )
58
+ self ._colors [i ] = self ._colors [i + 1 ] = 'red'
59
+ self ._display (self ._colors )
60
+ time .sleep (self ._speed )
61
+ self .data [i ],self .data [i + 1 ]= self .data [i + 1 ],self .data [i ]
62
+ self ._colors [i ] = self ._colors [i + 1 ] = 'lime'
63
+ self ._display (self ._colors )
64
+ time .sleep (self ._speed )
65
+ self ._colors [i ] = self ._colors [i + 1 ] = 'dodgerblue'
66
+ self ._colors [a :] = ['green' ]* (self .N - a )
67
+ self ._display (self ._colors )
68
+ self .__reset_colors ('green' )
69
+ self ._display (self ._colors )
70
+
71
+
72
+
73
+
74
+ if __name__ == '__main__' :
75
+ window = Style (theme = 'darkly' ).master
76
+ App (window ,'Bubble sort' )
77
+ window .mainloop ()
0 commit comments